-- Step 1: Add columns (level temporarily nullable to allow data migration)
ALTER TABLE "tags" ADD COLUMN "level" text;--> statement-breakpoint
ALTER TABLE "tags" ADD COLUMN "parent_page_id" integer;--> statement-breakpoint

-- Step 2: Set level for existing page tags
UPDATE "tags" SET "level" = 'page' WHERE "name" IN ('general', 'repetition', 'nationalities', 'vocations', 'hobbies', 'food-and-drink', 'social', 'home', 'body');--> statement-breakpoint

-- Step 3: Set level and parentPageId for existing subheading tag (none exist yet, will be created manually)
-- UPDATE "tags" SET "level" = 'subheading', "parent_page_id" = (SELECT id FROM "tags" WHERE "name" = 'body') WHERE "name" = 'parts-of-the-body';--> statement-breakpoint

-- Step 4: Insert grammar tags
INSERT INTO "tags" ("name", "description", "level") VALUES
  ('Noun', 'Noun', 'grammar'),
  ('Verb', 'Verb', 'grammar'),
  ('Adjective', 'Adjective', 'grammar'),
  ('Adverb', 'Adverb', 'grammar'),
  ('Preposition', 'Preposition', 'grammar'),
  ('Conjunction', 'Conjunction', 'grammar'),
  ('Interjection', 'Interjection', 'grammar'),
  ('Pronoun', 'Pronoun', 'grammar');--> statement-breakpoint

-- Step 5: Insert gender tags
INSERT INTO "tags" ("name", "description", "level") VALUES
  ('Masculine', 'Masculine gender', 'gender'),
  ('Feminine', 'Feminine gender', 'gender');--> statement-breakpoint

-- Step 6: Migrate word.type to word_tags (creating grammar tag associations)
INSERT INTO "word_tags" ("word_id", "tag_id")
SELECT w.id, t.id
FROM "words" w
JOIN "tags" t ON LOWER(w.type) = LOWER(t.name)
WHERE t.level = 'grammar';--> statement-breakpoint

-- Step 7: Migrate word.gender to word_tags (creating gender tag associations)
INSERT INTO "word_tags" ("word_id", "tag_id")
SELECT w.id, t.id
FROM "words" w
JOIN "tags" t ON (w.gender = 'm' AND t.name = 'Masculine') OR (w.gender = 'f' AND t.name = 'Feminine')
WHERE w.gender IS NOT NULL;--> statement-breakpoint

-- Step 8: Make level NOT NULL now that all rows have values
ALTER TABLE "tags" ALTER COLUMN "level" SET NOT NULL;--> statement-breakpoint

-- Step 9: Add foreign key constraint for self-reference
ALTER TABLE "tags" ADD CONSTRAINT "tags_parent_page_id_fkey" FOREIGN KEY ("parent_page_id") REFERENCES "tags"("id");--> statement-breakpoint

-- Step 10: Drop old columns from words table
ALTER TABLE "words" DROP COLUMN "type";--> statement-breakpoint
ALTER TABLE "words" DROP COLUMN "gender";