-- Drop foreign key constraints referencing tickets.id
ALTER TABLE "custom_field_values" DROP CONSTRAINT IF EXISTS "custom_field_values_ticket_id_tickets_id_fk";
ALTER TABLE "transactions" DROP CONSTRAINT IF EXISTS "transactions_ticket_id_tickets_id_fk";

-- Drop dependent indexes
DROP INDEX IF EXISTS "custom_field_values_ticket_id_idx";
DROP INDEX IF EXISTS "transactions_ticket_id_idx";

-- Clear all data from affected tables (UUIDs cannot cast to integer)
DELETE FROM "custom_field_values";
DELETE FROM "transactions";
DELETE FROM "tickets";

-- Alter column types with USING clause for empty tables
ALTER TABLE "custom_field_values" ALTER COLUMN "ticket_id" SET DATA TYPE integer USING (0);
ALTER TABLE "transactions" ALTER COLUMN "ticket_id" SET DATA TYPE integer USING (0);

-- Alter tickets.id to serial
ALTER TABLE "tickets" ALTER COLUMN "id" DROP DEFAULT;
ALTER TABLE "tickets" ALTER COLUMN "id" SET DATA TYPE integer USING (0);
ALTER TABLE "tickets" ALTER COLUMN "id" ADD GENERATED ALWAYS AS IDENTITY (sequence name "tickets_id_seq" INCREMENT BY 1 MINVALUE 1 MAXVALUE 2147483647 START WITH 1 CACHE 1);

-- Re-add foreign key constraints
ALTER TABLE "custom_field_values" ADD CONSTRAINT "custom_field_values_ticket_id_tickets_id_fk" FOREIGN KEY ("ticket_id") REFERENCES "public"."tickets"("id") ON DELETE cascade ON UPDATE no action;
ALTER TABLE "transactions" ADD CONSTRAINT "transactions_ticket_id_tickets_id_fk" FOREIGN KEY ("ticket_id") REFERENCES "public"."tickets"("id") ON DELETE cascade ON UPDATE no action;

-- Re-create indexes
CREATE INDEX "custom_field_values_ticket_id_idx" ON "custom_field_values" USING btree ("ticket_id");
CREATE INDEX "transactions_ticket_id_idx" ON "transactions" USING btree ("ticket_id");
