import { db } from '@/lib/db'
import { invites, users } from '@/lib/db/schema'
import { eq, and, isNull, gt } from 'drizzle-orm'
import { NextRequest, NextResponse } from 'next/server'
import bcrypt from 'bcryptjs'

export async function POST(request: NextRequest) {
  const { token, fullName, password } = await request.json()

  if (!token || !fullName || !password) {
    return NextResponse.json({ error: 'Missing required fields' }, { status: 400 })
  }

  if (password.length < 8) {
    return NextResponse.json(
      { error: 'Password must be at least 8 characters' },
      { status: 400 }
    )
  }

  // Validate invite
  const inviteResult = await db
    .select()
    .from(invites)
    .where(eq(invites.token, token))
    .limit(1)

  const invite = inviteResult[0]

  if (!invite) {
    return NextResponse.json({ error: 'Invalid invite link' }, { status: 400 })
  }
  if (invite.usedAt) {
    return NextResponse.json({ error: 'This invite has already been used' }, { status: 400 })
  }
  if (new Date(invite.expiresAt) < new Date()) {
    return NextResponse.json({ error: 'This invite has expired' }, { status: 400 })
  }

  // Check if user with this email already exists
  const existingUser = await db
    .select({ id: users.id })
    .from(users)
    .where(eq(users.email, invite.email))
    .limit(1)

  if (existingUser.length > 0) {
    return NextResponse.json(
      { error: 'An account with this email already exists' },
      { status: 409 }
    )
  }

  const passwordHash = await bcrypt.hash(password, 12)

  const newUser = await db
    .insert(users)
    .values({
      email: invite.email,
      passwordHash,
      fullName: fullName.trim(),
    })
    .returning({ id: users.id })

  // Mark invite as used
  await db
    .update(invites)
    .set({ usedAt: new Date(), usedBy: newUser[0].id })
    .where(eq(invites.token, token))

  return NextResponse.json({ success: true })
}
