-- Create charts table
CREATE TABLE `charts` (
	`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
	`name` text NOT NULL,
	`created_at` integer NOT NULL
);
--> statement-breakpoint
CREATE UNIQUE INDEX `charts_name_unique` ON `charts` (`name`);
--> statement-breakpoint

-- Insert default chart if candles exist
INSERT INTO `charts` (`name`, `created_at`)
SELECT 'Imported Data', CAST(strftime('%s', 'now') AS INTEGER)
WHERE EXISTS (SELECT 1 FROM `candles` LIMIT 1);
--> statement-breakpoint

-- Drop old unique index on candles.time
DROP INDEX IF EXISTS `candles_time_unique`;
--> statement-breakpoint

-- Add chart_id column to candles (nullable first for backfill)
ALTER TABLE `candles` ADD `chart_id` integer REFERENCES charts(id);
--> statement-breakpoint

-- Backfill existing candles with the default chart id
UPDATE `candles` SET `chart_id` = (SELECT `id` FROM `charts` WHERE `name` = 'Imported Data') WHERE `chart_id` IS NULL;
--> statement-breakpoint

-- Add chart_id column to annotations (nullable first for backfill)
ALTER TABLE `annotations` ADD `chart_id` integer REFERENCES charts(id);
--> statement-breakpoint

-- Backfill existing annotations with the default chart id
UPDATE `annotations` SET `chart_id` = (SELECT `id` FROM `charts` WHERE `name` = 'Imported Data') WHERE `chart_id` IS NULL;
--> statement-breakpoint

-- Recreate candles table with NOT NULL constraint and composite unique index
CREATE TABLE `candles_new` (
	`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
	`chart_id` integer NOT NULL REFERENCES charts(id),
	`time` integer NOT NULL,
	`open` real NOT NULL,
	`high` real NOT NULL,
	`low` real NOT NULL,
	`close` real NOT NULL
);
--> statement-breakpoint
INSERT INTO `candles_new` (`id`, `chart_id`, `time`, `open`, `high`, `low`, `close`)
SELECT `id`, `chart_id`, `time`, `open`, `high`, `low`, `close` FROM `candles`;
--> statement-breakpoint
DROP TABLE `candles`;
--> statement-breakpoint
ALTER TABLE `candles_new` RENAME TO `candles`;
--> statement-breakpoint
CREATE UNIQUE INDEX `candles_chart_time_unique` ON `candles` (`chart_id`, `time`);
--> statement-breakpoint

-- Recreate annotations table with NOT NULL constraint
CREATE TABLE `annotations_new` (
	`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
	`chart_id` integer NOT NULL REFERENCES charts(id),
	`timestamp` integer NOT NULL,
	`label_type` text NOT NULL,
	`geometry` text,
	`color` text DEFAULT '#3b82f6',
	`created_at` integer NOT NULL
);
--> statement-breakpoint
INSERT INTO `annotations_new` (`id`, `chart_id`, `timestamp`, `label_type`, `geometry`, `color`, `created_at`)
SELECT `id`, `chart_id`, `timestamp`, `label_type`, `geometry`, `color`, `created_at` FROM `annotations`;
--> statement-breakpoint
DROP TABLE `annotations`;
--> statement-breakpoint
ALTER TABLE `annotations_new` RENAME TO `annotations`;
