CREATE TABLE "support_messages" ( "id" serial PRIMARY KEY NOT NULL, "ticket_id" integer NOT NULL, "from_support" boolean DEFAULT false NOT NULL, "author_id" integer, "text" text, "file_id" text, "file_kind" text, "file_name" text, "at" timestamp with time zone DEFAULT now() NOT NULL ); --> statement-breakpoint CREATE TABLE "support_tickets" ( "id" serial PRIMARY KEY NOT NULL, "chat_id" bigint NOT NULL, "user_id" integer, "tg_name" text, "tg_username" text, "status" text DEFAULT 'open' NOT NULL, "unread" boolean DEFAULT true NOT NULL, "last_message_at" timestamp with time zone DEFAULT now() NOT NULL, "closed_at" timestamp with time zone, "created_at" timestamp with time zone DEFAULT now() NOT NULL ); --> statement-breakpoint ALTER TABLE "outbox" ALTER COLUMN "user_id" DROP NOT NULL;--> statement-breakpoint ALTER TABLE "support_messages" ADD CONSTRAINT "support_messages_ticket_id_support_tickets_id_fk" FOREIGN KEY ("ticket_id") REFERENCES "public"."support_tickets"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint ALTER TABLE "support_messages" ADD CONSTRAINT "support_messages_author_id_users_id_fk" FOREIGN KEY ("author_id") REFERENCES "public"."users"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint ALTER TABLE "support_tickets" ADD CONSTRAINT "support_tickets_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint CREATE INDEX "support_messages_ticket_idx" ON "support_messages" USING btree ("ticket_id");--> statement-breakpoint CREATE INDEX "support_tickets_status_idx" ON "support_tickets" USING btree ("status","last_message_at");--> statement-breakpoint CREATE UNIQUE INDEX "support_tickets_open_uq" ON "support_tickets" USING btree ("chat_id") WHERE "support_tickets"."status" = 'open';