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

type PostRow = Record<string, unknown> & { id: string };

export async function GET(request: Request) {
  try {
    const ownerId = requireOwner(request);
    const brandId = new URL(request.url).searchParams.get("brandId");
    if (!brandId) throw new Error("brandId가 필요합니다.");
    await ensureSchema();
    const db = rawDb();
    const posts = await db.prepare("SELECT * FROM scheduled_posts WHERE owner_id = ? AND brand_id = ? ORDER BY scheduled_for DESC LIMIT 200")
      .bind(ownerId, brandId).all<PostRow>();
    const items = [];
    for (const post of posts.results) {
      const targets = await db.prepare("SELECT id, account_id, platform, status, external_post_id, error_message, published_at FROM scheduled_post_targets WHERE post_id = ? ORDER BY platform")
        .bind(post.id).all();
      items.push({ ...post, targets: targets.results });
    }
    return Response.json({ posts: items });
  } catch (error) { return apiError(error); }
}

export async function POST(request: Request) {
  try {
    const ownerId = requireOwner(request);
    const body = await request.json() as {
      brandId?: string; content?: string; mediaUrl?: string; mediaType?: "image" | "video";
      altText?: string; scheduledFor?: number; timezone?: string; platforms?: Platform[];
    };
    const content = body.content?.trim();
    const platforms = [...new Set(body.platforms || [])].filter((item): item is Platform => item === "instagram" || item === "threads");
    if (!body.brandId || !content) throw new Error("브랜드와 게시글 내용을 입력해주세요.");
    if (!platforms.length) throw new Error("게시할 플랫폼을 선택해주세요.");
    if (!body.scheduledFor || !Number.isFinite(body.scheduledFor)) throw new Error("예약 시간을 선택해주세요.");
    if (platforms.includes("instagram") && !body.mediaUrl?.trim()) throw new Error("Instagram 예약에는 공개 이미지 또는 영상 URL이 필요합니다.");
    await ensureSchema();
    const db = rawDb();
    const brand = await db.prepare("SELECT id FROM brands WHERE id = ? AND owner_id = ?").bind(body.brandId, ownerId).first();
    if (!brand) throw new Error("브랜드를 찾을 수 없습니다.");
    const id = crypto.randomUUID();
    const now = Date.now();
    await db.prepare(`INSERT INTO scheduled_posts
      (id, owner_id, brand_id, content, media_url, media_type, alt_text, scheduled_for, timezone, status, created_at, updated_at)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'scheduled', ?, ?)`)
      .bind(id, ownerId, body.brandId, content.slice(0, 2200), body.mediaUrl?.trim() || null,
        body.mediaType || (body.mediaUrl ? "image" : null), body.altText?.trim().slice(0, 1000) || null,
        body.scheduledFor, body.timezone || "Asia/Seoul", now, now).run();
    for (const platform of platforms) {
      const account = await db.prepare("SELECT id FROM social_accounts WHERE owner_id = ? AND brand_id = ? AND platform = ? AND status = 'connected' ORDER BY updated_at DESC LIMIT 1")
        .bind(ownerId, body.brandId, platform).first<{ id: string }>();
      await db.prepare(`INSERT INTO scheduled_post_targets
        (id, post_id, account_id, platform, status, created_at, updated_at) VALUES (?, ?, ?, ?, 'scheduled', ?, ?)`)
        .bind(crypto.randomUUID(), id, account?.id || null, platform, now, now).run();
    }
    return Response.json({ id }, { status: 201 });
  } catch (error) { return apiError(error); }
}
