CREATE TABLE `organization_memberships` (
	`id` text PRIMARY KEY NOT NULL,
	`organization_id` text NOT NULL,
	`user_id` text NOT NULL,
	`role` text DEFAULT 'user' 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 cascade,
	FOREIGN KEY (`user_id`) REFERENCES `user`(`id`) ON UPDATE no action ON DELETE cascade
);
--> statement-breakpoint
CREATE UNIQUE INDEX `organization_memberships_organization_user_unique` ON `organization_memberships` (`organization_id`,`user_id`);--> statement-breakpoint
CREATE INDEX `organization_memberships_organization_id_idx` ON `organization_memberships` (`organization_id`);--> statement-breakpoint
CREATE INDEX `organization_memberships_user_id_idx` ON `organization_memberships` (`user_id`);--> statement-breakpoint
INSERT INTO `organization_memberships` (`id`, `organization_id`, `user_id`, `role`)
SELECT lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-' || lower(hex(randomblob(2))) || '-' || lower(hex(randomblob(2))) || '-' || lower(hex(randomblob(6))),
	organizations.`id`,
	user.`id`,
	CASE WHEN user.`role` = 'admin' THEN 'admin' ELSE 'user' END
FROM `organizations`
CROSS JOIN `user`
WHERE NOT EXISTS (
	SELECT 1
	FROM `organization_memberships`
	WHERE `organization_memberships`.`organization_id` = organizations.`id`
		AND `organization_memberships`.`user_id` = user.`id`
);
