-- AlterTable
ALTER TABLE "tags" ADD COLUMN     "tag_group_id" BIGINT,
ADD COLUMN     "sort_order" INTEGER NOT NULL DEFAULT 0;

-- CreateTable
CREATE TABLE "tag_groups" (
    "tag_group_id" BIGSERIAL NOT NULL,
    "group_name" TEXT NOT NULL,
    "group_icon" TEXT,
    "group_color" TEXT,
    "sort_order" INTEGER NOT NULL DEFAULT 0,
    "created_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updated_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "tag_groups_pkey" PRIMARY KEY ("tag_group_id")
);

-- CreateIndex
CREATE UNIQUE INDEX "tag_groups_group_name_key" ON "tag_groups"("group_name");

-- CreateIndex
CREATE INDEX "tags_tag_group_id_idx" ON "tags"("tag_group_id");

-- CreateIndex
CREATE INDEX "tags_tag_group_id_sort_order_idx" ON "tags"("tag_group_id", "sort_order");

-- AddForeignKey
ALTER TABLE "tags" ADD CONSTRAINT "tags_tag_group_id_fkey" FOREIGN KEY ("tag_group_id") REFERENCES "tag_groups"("tag_group_id") ON DELETE SET NULL ON UPDATE NO ACTION;

-- Seed: insert 3 default tag groups
INSERT INTO "tag_groups" ("group_name", "sort_order", "created_at", "updated_at") VALUES
  ('物流渠道', 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP),
  ('印刷位置', 2, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP),
  ('印刷工艺', 3, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP);

-- Seed: assign existing tags to groups
UPDATE "tags" SET "tag_group_id" = (SELECT "tag_group_id" FROM "tag_groups" WHERE "group_name" = '物流渠道')
  WHERE "tag_name" IN ('包邮', '不包邮');
UPDATE "tags" SET "tag_group_id" = (SELECT "tag_group_id" FROM "tag_groups" WHERE "group_name" = '印刷位置')
  WHERE "tag_name" IN ('单面印', '双面印');
UPDATE "tags" SET "tag_group_id" = (SELECT "tag_group_id" FROM "tag_groups" WHERE "group_name" = '印刷工艺')
  WHERE "tag_name" IN ('烫画', '直喷', '不打印');

-- Seed: assign sortOrder within each group by tag_id
WITH ordered AS (
  SELECT "tag_id",
         ROW_NUMBER() OVER (PARTITION BY "tag_group_id" ORDER BY "tag_id") AS rn
  FROM "tags"
  WHERE "tag_group_id" IS NOT NULL
)
UPDATE "tags" SET "sort_order" = ordered.rn
FROM ordered
WHERE "tags"."tag_id" = ordered."tag_id";
