/**
 * Seed admin + 6 categories cho Finzone v2.
 *
 * Usage:
 *   1. App phải đang chạy (local hoặc prod) tại BETTER_AUTH_URL
 *   2. SEED_ADMIN_PASSWORD trong .env
 *   3. npm run seed
 *
 * Idempotent — chạy nhiều lần không nhân bản.
 *
 * NOTE: Password hash phải khớp với better-auth (scrypt, không phải bcrypt).
 * Cách an toàn nhất: gọi /api/auth/sign-up/email để better-auth tự hash đúng,
 * rồi promote role="admin" qua Prisma. KHÔNG dùng bcrypt.hash() trực tiếp.
 */
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

const ADMIN_EMAIL = process.env.SEED_ADMIN_EMAIL ?? "giang@vitaminlux.com";
const ADMIN_PASSWORD = process.env.SEED_ADMIN_PASSWORD ?? "$SEE...WORD";
const ADMIN_NAME = process.env.SEED_ADMIN_NAME ?? "Giang Trường";
const APP_URL =
  process.env.BETTER_AUTH_URL ??
  process.env.NEXT_PUBLIC_SITE_URL ??
  "http://localhost:3000";

const CATEGORIES = [
  { slug: "chung-khoan", name: "Chứng khoán", description: "Tin VN-Index, cổ phiếu, dòng tiền và phân tích phiên." },
  { slug: "crypto", name: "Crypto", description: "Bitcoin, altcoin, DeFi, on-chain và xu hướng thị trường." },
  { slug: "forex", name: "Forex", description: "Cập nhật tỷ giá, USD/VND, các cặp ngoại tệ chính." },
  { slug: "vang", name: "Vàng", description: "Giá vàng SJC, vàng nhẫn, vàng thế giới." },
  { slug: "phan-tich", name: "Phân tích", description: "Bài phân tích chuyên sâu, báo cáo, nhận định thị trường." },
  { slug: "tai-chinh-ca-nhan", name: "Tài chính cá nhân", description: "Quản lý tiền, tiết kiệm, đầu tư cá nhân, FIRE." },
];

async function main() {
  console.log("→ Seeding admin user via better-auth API…");
  console.log(`  · APP_URL = ${APP_URL}`);

  const existing = await prisma.user.findUnique({ where: { email: ADMIN_EMAIL } });

  if (existing) {
    // Already exists — chỉ promote role, KHÔNG đổi password (giữ nguyên hash đúng từ
    // lần sign-up gần nhất). Nếu cần reset password, xóa tay rồi chạy lại.
    await prisma.user.update({
      where: { email: ADMIN_EMAIL },
      data: { role: "admin", name: ADMIN_NAME, emailVerified: true },
    });
    console.log(`  · existing admin promoted: ${ADMIN_EMAIL}`);
  } else {
    // Tạo user mới qua better-auth sign-up endpoint (hash password đúng format scrypt)
    const res = await fetch(`${APP_URL}/api/auth/sign-up/email`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        email: ADMIN_EMAIL,
        password: ADMIN_PASSWORD,
        name: ADMIN_NAME,
      }),
    });
    if (!res.ok) {
      const text = await res.text();
      throw new Error(`sign-up failed (HTTP ${res.status}): ${text}`);
    }
    // Promote role + verify email qua Prisma
    await prisma.user.update({
      where: { email: ADMIN_EMAIL },
      data: { role: "admin", emailVerified: true },
    });
    console.log(`  · created admin: ${ADMIN_EMAIL}`);
  }

  console.log("\n→ Seeding categories…");
  for (const [i, cat] of CATEGORIES.entries()) {
    await prisma.category.upsert({
      where: { slug: cat.slug },
      update: { name: cat.name, description: cat.description, order: i },
      create: { ...cat, order: i },
    });
    console.log(`  · ${cat.slug} ✓`);
  }

  console.log("\n→ Seeding default settings…");
  const settings = [
    { key: "site.title", value: "Finzone v2", category: "site" },
    { key: "site.description", value: "Trang tin tài chính cho nhà đầu tư Việt Nam", category: "site" },
    { key: "site.url", value: "https://v2.finzone.io.vn", category: "site" },
    { key: "site.locale", value: "vi-VN", category: "site" },
    { key: "ai.openai_base_url", value: "http://192.168.40.11:2012/v1", category: "ai", isSecret: false },
    { key: "ai.openai_model", value: "cx/gpt-5.5", category: "ai", isSecret: false },
    { key: "ai.openai_api_key", value: "", category: "ai", isSecret: true },
    { key: "seo.default_focus_min_score", value: "70", category: "seo" },
  ];
  for (const s of settings) {
    await prisma.setting.upsert({
      where: { key: s.key },
      update: { value: s.value, category: s.category, isSecret: s.isSecret ?? false },
      create: { key: s.key, value: s.value, category: s.category, isSecret: s.isSecret ?? false },
    });
  }
  console.log(`  · ${settings.length} settings`);

  console.log("\n✅ Seed done.");
}

main()
  .catch((e) => {
    console.error(e);
    process.exit(1);
  })
  .finally(() => prisma.$disconnect());
