CREATE TABLE `contract_rooms` (
	`contract_id` text NOT NULL,
	`room_id` text NOT NULL,
	PRIMARY KEY(`contract_id`, `room_id`),
	FOREIGN KEY (`contract_id`) REFERENCES `contracts`(`id`) ON UPDATE no action ON DELETE cascade,
	FOREIGN KEY (`room_id`) REFERENCES `rooms`(`id`) ON UPDATE no action ON DELETE restrict
);
--> statement-breakpoint
CREATE INDEX `contract_rooms_room_id_idx` ON `contract_rooms` (`room_id`);--> statement-breakpoint
INSERT INTO `contract_rooms`("contract_id", "room_id") SELECT "id", "room_id" FROM `contracts` WHERE "room_id" IS NOT NULL;--> statement-breakpoint
PRAGMA foreign_keys=OFF;--> statement-breakpoint
CREATE TABLE `__new_contracts` (
	`id` text PRIMARY KEY NOT NULL,
	`organization_id` text NOT NULL,
	`client_id` text NOT NULL,
	`service_id` text,
	`license_fee_gbp` real DEFAULT 0 NOT NULL,
	`deposit_gbp` real DEFAULT 0 NOT NULL,
	`start_date` text NOT NULL,
	`end_date` text NOT NULL,
	`billed_to` text,
	`status` text DEFAULT 'draft' NOT NULL,
	`created_at` integer DEFAULT (cast(unixepoch('subsecond') * 1000 as integer)) NOT NULL,
	`updated_at` integer DEFAULT (cast(unixepoch('subsecond') * 1000 as integer)) NOT NULL,
	`archived_at` integer,
	FOREIGN KEY (`organization_id`) REFERENCES `organizations`(`id`) ON UPDATE no action ON DELETE restrict,
	FOREIGN KEY (`client_id`) REFERENCES `clients`(`id`) ON UPDATE no action ON DELETE restrict,
	FOREIGN KEY (`service_id`) REFERENCES `services`(`id`) ON UPDATE no action ON DELETE restrict
);
--> statement-breakpoint
INSERT INTO `__new_contracts`("id", "organization_id", "client_id", "service_id", "license_fee_gbp", "deposit_gbp", "start_date", "end_date", "billed_to", "status", "created_at", "updated_at", "archived_at") SELECT "id", "organization_id", "client_id", "service_id", "license_fee_gbp", "deposit_gbp", "start_date", "end_date", "billed_to", "status", "created_at", "updated_at", "archived_at" FROM `contracts`;--> statement-breakpoint
DROP TABLE `contracts`;--> statement-breakpoint
ALTER TABLE `__new_contracts` RENAME TO `contracts`;--> statement-breakpoint
PRAGMA foreign_keys=ON;--> statement-breakpoint
CREATE INDEX `contracts_organization_id_idx` ON `contracts` (`organization_id`);--> statement-breakpoint
CREATE INDEX `contracts_client_id_idx` ON `contracts` (`client_id`);--> statement-breakpoint
CREATE INDEX `contracts_service_id_idx` ON `contracts` (`service_id`);
