import { apiError, requireOwner } from "@/lib/auth";
import { ensureSchema, rawDb } from "@/lib/db";

type BrandRow = { id: string; name: string; description: string; color: string; created_at: number; updated_at: number };

export async function GET(request: Request) {
  try {
    const ownerId = requireOwner(request);
    await ensureSchema();
    const db = rawDb();
    let result = await db.prepare("SELECT id, name, description, color, created_at, updated_at FROM brands WHERE owner_id = ? ORDER BY created_at")
      .bind(ownerId).all<BrandRow>();
    if (!result.results.length) {
      const id = crypto.randomUUID();
      const now = Date.now();
      await db.prepare("INSERT INTO brands (id, owner_id, name, description, color, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)")
        .bind(id, ownerId, "KS Company", "브랜드별 Instagram과 Threads 게시물을 관리하세요.", "#7657e8", now, now).run();
      result = await db.prepare("SELECT id, name, description, color, created_at, updated_at FROM brands WHERE owner_id = ? ORDER BY created_at")
        .bind(ownerId).all<BrandRow>();
    }
    return Response.json({ brands: result.results });
  } catch (error) { return apiError(error); }
}

export async function POST(request: Request) {
  try {
    const ownerId = requireOwner(request);
    await ensureSchema();
    const body = await request.json() as { name?: string; description?: string; color?: string };
    const name = body.name?.trim();
    if (!name || name.length > 60) throw new Error("브랜드 이름을 1~60자로 입력해주세요.");
    const id = crypto.randomUUID();
    const now = Date.now();
    await rawDb().prepare("INSERT INTO brands (id, owner_id, name, description, color, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)")
      .bind(id, ownerId, name, body.description?.trim().slice(0, 500) || "", body.color || "#7657e8", now, now).run();
    return Response.json({ id }, { status: 201 });
  } catch (error) { return apiError(error); }
}
