import { NextResponse } from 'next/server'
import { auth } from '@/auth'
import { sendListingPublishedConfirmation } from '@/lib/email/send-listing-published'
import { insertListingTransactional, listingSubmitSchema } from '@/lib/listings'

export const dynamic = 'force-dynamic'

/** Zapis ogłoszenia z formularza (JSON). Zdjęcia: POST /api/listings/[id]/images (multipart, pole `files`). */
export async function POST(req: Request) {
  try {
    const session = await auth()
    if (!session?.user?.id) {
      return NextResponse.json({ error: 'Musisz się zalogować, aby opublikować ogłoszenie.' }, { status: 401 })
    }

    let body: unknown
    try {
      body = await req.json()
    } catch {
      return NextResponse.json({ error: 'Niepoprawny format JSON.' }, { status: 400 })
    }

    const parsed = listingSubmitSchema.safeParse(body)
    if (!parsed.success) {
      const msg = parsed.error.issues[0]?.message ?? 'Niepoprawne dane ogłoszenia.'
      return NextResponse.json({ error: msg }, { status: 400 })
    }

    try {
      const { id, slug } = await insertListingTransactional(session.user.id, parsed.data)
      const durationDays = Number.parseInt(parsed.data.duration, 10)
      const emailResult = await sendListingPublishedConfirmation({
        to: parsed.data.email,
        title: parsed.data.modelTitle,
        slug,
        categoryId: parsed.data.category,
        durationDays: Number.isFinite(durationDays) ? durationDays : 30,
        contactName: parsed.data.contactPerson,
      })
      const emailSkipped = !emailResult.sent && emailResult.reason === 'disabled'
      if (!emailResult.sent && emailResult.reason === 'error') {
        console.warn('listing confirmation email not sent', emailResult.message)
      }
      return NextResponse.json({
        ok: true,
        id,
        slug,
        emailSent: emailResult.sent,
        emailSkipped,
      })
    } catch (e: unknown) {
      const err = e as { code?: string; errno?: number; sqlMessage?: string }
      if (err.code === 'ER_DUP_ENTRY') {
        return NextResponse.json({ error: 'Konflikt unikalnego identyfikatora — spróbuj ponownie.' }, { status: 409 })
      }
      if (err.sqlMessage?.includes('JSON') || err.sqlMessage?.includes('json')) {
        return NextResponse.json(
          {
            error:
              'Baza nie przyjęła pola JSON — potrzebna wersja MySQL/MariaDB z typem JSON. Szczegóły w logach serwera.',
          },
          { status: 500 },
        )
      }
      console.error('listing insert', e)
      return NextResponse.json({ error: 'Nie udało się zapisać ogłoszenia. Spróbuj ponownie.' }, { status: 500 })
    }
  } catch (e) {
    console.error('listing route', e)
    return NextResponse.json({ error: 'Błąd serwera.' }, { status: 500 })
  }
}

export type ListingPostResponse =
  | { ok: true; id: string; slug: string; emailSent?: boolean; emailSkipped?: boolean }
  | { error: string }
