CREATE TABLE "notification_outbox" (
	"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
	"provider" text NOT NULL,
	"kind" text NOT NULL,
	"link_id" uuid,
	"workspace_id" text,
	"destination" text NOT NULL,
	"payload" jsonb NOT NULL,
	"idempotency_key" text NOT NULL,
	"status" text DEFAULT 'pending' NOT NULL,
	"attempts" integer DEFAULT 0 NOT NULL,
	"max_attempts" integer DEFAULT 5 NOT NULL,
	"due_at" timestamp with time zone DEFAULT now() NOT NULL,
	"leased_until" timestamp with time zone,
	"leased_by" text,
	"delivered_at" timestamp with time zone,
	"external_id" text,
	"error" text,
	"requested_by_user_id" uuid,
	"created_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
DROP INDEX "channel_links_platform_channel_key";--> statement-breakpoint
ALTER TABLE "channel_links" ADD COLUMN "workspace_id" text DEFAULT '' NOT NULL;--> statement-breakpoint
ALTER TABLE "channel_links" ADD COLUMN "linked_by_user_id" uuid;--> statement-breakpoint
ALTER TABLE "channel_links" ADD COLUMN "updated_at" timestamp with time zone DEFAULT now() NOT NULL;--> statement-breakpoint
ALTER TABLE "notification_outbox" ADD CONSTRAINT "notification_outbox_link_id_channel_links_id_fk" FOREIGN KEY ("link_id") REFERENCES "public"."channel_links"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "notification_outbox" ADD CONSTRAINT "notification_outbox_requested_by_user_id_users_id_fk" FOREIGN KEY ("requested_by_user_id") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
CREATE UNIQUE INDEX "notification_outbox_idempotency_key" ON "notification_outbox" USING btree ("idempotency_key");--> statement-breakpoint
CREATE INDEX "notification_outbox_claimable_idx" ON "notification_outbox" USING btree ("provider","status","due_at");--> statement-breakpoint
CREATE INDEX "notification_outbox_link_idx" ON "notification_outbox" USING btree ("link_id");--> statement-breakpoint
ALTER TABLE "channel_links" ADD CONSTRAINT "channel_links_linked_by_user_id_users_id_fk" FOREIGN KEY ("linked_by_user_id") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
CREATE UNIQUE INDEX "channel_links_platform_workspace_channel_key" ON "channel_links" USING btree ("platform","workspace_id","channel_id");
