import { NextResponse } from "next/server";
import { createStripeClient } from "@/lib/stripe/server";
import { createClient } from "@/lib/supabase/server";
import { sql } from "@/lib/db/postgres";
import { logApiError } from "@/lib/api/security";
import { getNoteCover } from "@/lib/notes/note-covers";
import { STICKERS } from "@/lib/notes/note-stickers";
import { NOTE_TEMPLATES } from "@/lib/notes/note-templates";
import { hasFullDesignAccess } from "@/lib/notes/design-access";

export async function POST(req: Request) {
  try {
    const supabase = await createClient();
    const {
      data: { user },
    } = await supabase.auth.getUser();
    if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

    const { designId } = await req.json();
    if (typeof designId !== "string") return NextResponse.json({ error: "Unknown design" }, { status: 404 });

    const builtinCover = getNoteCover(designId);
    const builtinSticker = STICKERS.find((sticker) => sticker.id === designId);
    const builtinTemplate = NOTE_TEMPLATES.find((template) => template.id === designId);
    let item: { id: string; name: string; price: number; creatorId?: string; type: "cover" | "sticker" | "template" } | null =
      builtinCover
        ? { id: builtinCover.id, name: builtinCover.name, price: builtinCover.price, type: "cover" }
        : builtinSticker
          ? { id: builtinSticker.id, name: builtinSticker.label, price: builtinSticker.price, type: "sticker" }
          : builtinTemplate
            ? { id: builtinTemplate.id, name: builtinTemplate.name, price: builtinTemplate.price, type: "template" }
            : null;

    if (!item) {
      const { rows } = await sql<{ id: string; name: string; price_cents: number; creator_id: string }>`
        SELECT id, name, price_cents, creator_id FROM note_designs
        WHERE id = ${designId} AND is_published = true LIMIT 1
      `;
      if (rows[0]) {
        item = {
          id: rows[0].id,
          name: rows[0].name,
          price: rows[0].price_cents,
          creatorId: rows[0].creator_id,
          type: "cover",
        };
      }
    }

    if (!item) {
      const { rows } = await sql<{ id: string; name: string; price_cents: number; creator_id: string }>`
        SELECT id, name, price_cents, creator_id FROM note_design_templates
        WHERE id = ${designId} AND is_published = true LIMIT 1
      `;
      if (rows[0]) {
        item = {
          id: rows[0].id,
          name: rows[0].name,
          price: rows[0].price_cents,
          creatorId: rows[0].creator_id,
          type: "template",
        };
      }
    }

    if (!item) return NextResponse.json({ error: "Unknown design" }, { status: 404 });
    if (item.price <= 0) {
      return NextResponse.json({ error: "This design is already free" }, { status: 400 });
    }
    if (item.creatorId === user.id) {
      return NextResponse.json({ error: "You already own your own design" }, { status: 400 });
    }
    if (hasFullDesignAccess(user.email)) {
      return NextResponse.json({ error: "Your account already has full design access" }, { status: 400 });
    }

    const { rows: owned } = await sql`
      SELECT id FROM note_design_purchases WHERE user_id = ${user.id} AND design_id = ${item.id} LIMIT 1
    `;
    if (owned[0]) {
      return NextResponse.json({ error: "You already own this design" }, { status: 400 });
    }

    const stripe = createStripeClient();
    const { rows } = await sql<{ stripe_customer_id: string | null }>`
      SELECT stripe_customer_id FROM user_subscriptions WHERE user_id = ${user.id} LIMIT 1
    `;
    let customerId = rows[0]?.stripe_customer_id ?? null;

    if (!customerId) {
      const customer = await stripe.customers.create({
        email: user.email,
        metadata: { supabase_user_id: user.id },
      });
      customerId = customer.id;
      await sql`
        INSERT INTO user_subscriptions (user_id, stripe_customer_id, plan, status)
        VALUES (${user.id}, ${customerId}, 'free', 'active')
        ON CONFLICT (user_id) DO UPDATE SET stripe_customer_id = EXCLUDED.stripe_customer_id
      `;
    }

    const appUrl = process.env.NEXT_PUBLIC_APP_URL || new URL(req.url).origin;
    const session = await stripe.checkout.sessions.create({
      customer: customerId,
      mode: "payment",
      line_items: [
        {
          price_data: {
            currency: "eur",
            unit_amount: item.price,
            product_data: {
              name: `Mindavio ${item.type === "sticker" ? "Sticker" : item.type === "template" ? "Vorlage" : "Notiz-Design"}: ${item.name}`,
            },
          },
          quantity: 1,
        },
      ],
      success_url: `${appUrl}/notes/marketplace?purchased=${item.id}`,
      cancel_url: `${appUrl}/notes/marketplace?canceled=1`,
      metadata: {
        user_id: user.id,
        design_id: item.id,
        design_type: item.type,
      },
    });

    return NextResponse.json({ url: session.url });
  } catch (error) {
    logApiError("Note design checkout POST error", error);
    const msg = error instanceof Error ? error.message : "Unknown error";
    return NextResponse.json({ error: msg }, { status: msg === "Stripe is not configured" ? 503 : 500 });
  }
}
