-- Phase 4: Add lists, list_shares, list_items tables.
-- Additive migration only — no DROP, TRUNCATE, or ALTER of existing tables.
--
-- D-01: lists.is_shared defaults to true (collaborative household use case)
-- D-02: list_shares join table is member-count-agnostic
-- D-13: list_items.rank is a fractional-indexing varchar string
CREATE TABLE `lists` (
	`id` int AUTO_INCREMENT NOT NULL,
	`owner_id` int NOT NULL,
	`name` varchar(255) NOT NULL,
	`is_shared` boolean NOT NULL DEFAULT true,
	`created_at` timestamp NOT NULL DEFAULT (now()),
	`updated_at` timestamp DEFAULT (now()) ON UPDATE CURRENT_TIMESTAMP,
	CONSTRAINT `lists_id` PRIMARY KEY(`id`)
);
--> statement-breakpoint
CREATE TABLE `list_shares` (
	`id` int AUTO_INCREMENT NOT NULL,
	`list_id` int NOT NULL,
	`user_id` int NOT NULL,
	`created_at` timestamp NOT NULL DEFAULT (now()),
	CONSTRAINT `list_shares_id` PRIMARY KEY(`id`),
	CONSTRAINT `uniq_list_share` UNIQUE(`list_id`,`user_id`)
);
--> statement-breakpoint
CREATE TABLE `list_items` (
	`id` int AUTO_INCREMENT NOT NULL,
	`list_id` int NOT NULL,
	`text` varchar(500) NOT NULL,
	`checked` boolean NOT NULL DEFAULT false,
	`rank` varchar(255) NOT NULL,
	`created_at` timestamp NOT NULL DEFAULT (now()),
	`updated_at` timestamp DEFAULT (now()) ON UPDATE CURRENT_TIMESTAMP,
	CONSTRAINT `list_items_id` PRIMARY KEY(`id`)
);
--> statement-breakpoint
ALTER TABLE `lists` ADD CONSTRAINT `lists_owner_id_users_id_fk` FOREIGN KEY (`owner_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE `list_shares` ADD CONSTRAINT `list_shares_list_id_lists_id_fk` FOREIGN KEY (`list_id`) REFERENCES `lists`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE `list_shares` ADD CONSTRAINT `list_shares_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE `list_items` ADD CONSTRAINT `list_items_list_id_lists_id_fk` FOREIGN KEY (`list_id`) REFERENCES `lists`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
CREATE INDEX `idx_lists_owner_id` ON `lists` (`owner_id`);--> statement-breakpoint
CREATE INDEX `idx_list_shares_user_id` ON `list_shares` (`user_id`);--> statement-breakpoint
CREATE INDEX `idx_list_items_list_id_rank` ON `list_items` (`list_id`,`rank`);--> statement-breakpoint
CREATE INDEX `idx_list_items_list_id_checked` ON `list_items` (`list_id`,`checked`);
