import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/lib/auth'
import { prisma } from '@/lib/prisma'
import bcrypt from 'bcryptjs'

// GET all microsites for the logged-in user
export async function GET() {
  try {
    const session = await auth()

    if (!session?.user?.id) {
      return NextResponse.json(
        { success: false, error: 'Unauthorized' },
        { status: 401 }
      )
    }

    const microsites = await prisma.microsite.findMany({
      where: {
        userId: session.user.id,
      },
      include: {
        links: {
          orderBy: {
            order: 'asc',
          },
        },
      },
      orderBy: {
        createdAt: 'desc',
      },
    })

    return NextResponse.json({ success: true, data: microsites })
  } catch (error) {
    return NextResponse.json(
      { success: false, error: 'Failed to fetch microsites' },
      { status: 500 }
    )
  }
}

// POST create new microsite
export async function POST(request: NextRequest) {
  try {
    const session = await auth()

    if (!session?.user?.id) {
      return NextResponse.json(
        { success: false, error: 'Unauthorized' },
        { status: 401 }
      )
    }

    const body = await request.json()
    interface LinkInput {
      label: string
      url: string
      shortLinkId?: bigint | null
    }
    const { slug, title, bio, profilePicture, theme, password, links } = body as {
      slug: string
      title: string
      bio?: string
      profilePicture?: string
      theme?: string
      password?: string
      links?: LinkInput[]
    }

    // Validate required fields
    if (!slug || !title) {
      return NextResponse.json(
        { success: false, error: 'Slug and title are required' },
        { status: 400 }
      )
    }

    // Check if slug already exists in microsites
    const existingMicrosite = await prisma.microsite.findUnique({
      where: { slug },
    })

    if (existingMicrosite) {
      return NextResponse.json(
        { success: false, error: 'This slug is already taken' },
        { status: 400 }
      )
    }

    // Check if slug conflicts with existing short link code
    const existingShortLink = await prisma.shortLink.findFirst({
      where: {
        code: slug,
        deletedAt: null
      },
    })

    if (existingShortLink) {
      return NextResponse.json(
        { success: false, error: 'Slug ini sudah dipakai oleh short link' },
        { status: 400 }
      )
    }

    // Hash password if provided
    let hashedPassword = null
    if (password) {
      hashedPassword = await bcrypt.hash(password, 10)
    }

    // Create microsite with links
    const microsite = await prisma.microsite.create({
      data: {
        userId: session.user.id,
        slug,
        title,
        bio: bio || null,
        profilePicture: profilePicture || null,
        theme: theme || 'default',
        password: hashedPassword,
        links: {
          create: links?.map((link: LinkInput, index: number) => ({
            label: link.label,
            url: link.url,
            order: index,
            shortLinkId: link.shortLinkId || null,
          })) || [],
        },
      },
      include: {
        links: true,
      },
    })

    return NextResponse.json({ success: true, data: microsite }, { status: 201 })
  } catch (error) {
    console.error('Error creating microsite:', error)
    return NextResponse.json(
      { success: false, error: 'Failed to create microsite' },
      { status: 500 }
    )
  }
}
