ALTER TABLE "channel_members" ADD COLUMN "is_closed" boolean DEFAULT false NOT NULL;
--> statement-breakpoint
INSERT INTO "channels" ("workspace_id", "type", "name", "created_by", "member_count")
SELECT
	w."id",
	'public'::"channel_type",
	d."name",
	creator."user_id",
	(SELECT count(*)::integer FROM "workspace_members" wm WHERE wm."workspace_id" = w."id" AND wm."deactivated_at" IS NULL)
FROM "workspaces" w
CROSS JOIN (VALUES ('general'), ('random')) AS d("name")
JOIN LATERAL (
	SELECT wm."user_id"
	FROM "workspace_members" wm
	WHERE wm."workspace_id" = w."id" AND wm."deactivated_at" IS NULL
	ORDER BY CASE wm."role" WHEN 'owner' THEN 0 WHEN 'admin' THEN 1 ELSE 2 END, wm."joined_at"
	LIMIT 1
) creator ON true
WHERE NOT EXISTS (
	SELECT 1 FROM "channels" c
	WHERE c."workspace_id" = w."id" AND c."type" = 'public' AND lower(c."name") = d."name"
);
--> statement-breakpoint
INSERT INTO "channel_seq" ("channel_id", "last_seq")
SELECT c."id", 0
FROM "channels" c
WHERE c."type" = 'public'
	AND lower(c."name") IN ('general', 'random')
	AND NOT EXISTS (SELECT 1 FROM "channel_seq" s WHERE s."channel_id" = c."id");
--> statement-breakpoint
INSERT INTO "channel_members" ("channel_id", "user_id", "role")
SELECT
	c."id",
	wm."user_id",
	CASE WHEN wm."user_id" = c."created_by" THEN 'owner' ELSE 'member' END
FROM "channels" c
JOIN "workspace_members" wm ON wm."workspace_id" = c."workspace_id" AND wm."deactivated_at" IS NULL
WHERE c."type" = 'public' AND lower(c."name") IN ('general', 'random')
ON CONFLICT ("channel_id", "user_id") DO NOTHING;
--> statement-breakpoint
UPDATE "channels" c
SET "member_count" = (SELECT count(*)::integer FROM "channel_members" cm WHERE cm."channel_id" = c."id")
WHERE c."type" = 'public' AND lower(c."name") IN ('general', 'random');
