import { NextRequest, NextResponse } from 'next/server'
import { requireStaffSession } from '@/lib/auth-helpers'
import { prisma } from '@/lib/prisma'
import { storageService } from '@/lib/services/storage-service'

const MAX_FILE_SIZE = 5 * 1024 * 1024 // 5MB
const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/webp']

/**
 * POST /api/v1/profile/photo
 * Upload profile photo
 */
export async function POST(request: NextRequest) {
  try {
    const session = await requireStaffSession()

    // Check if storage is configured
    const isConfigured = await storageService.isConfigured()
    if (!isConfigured) {
      return NextResponse.json(
        { error: 'Storage not configured. Please configure S3/MinIO settings in Admin Settings.' },
        { status: 400 }
      )
    }

    // Parse multipart form data
    const formData = await request.formData()
    const file = formData.get('photo') as File | null

    if (!file) {
      return NextResponse.json({ error: 'No photo file provided' }, { status: 400 })
    }

    // Validate file type
    if (!ALLOWED_TYPES.includes(file.type)) {
      return NextResponse.json(
        { error: 'Invalid file type. Allowed: JPEG, PNG, WebP' },
        { status: 400 }
      )
    }

    // Validate file size
    if (file.size > MAX_FILE_SIZE) {
      return NextResponse.json(
        { error: 'File too large. Maximum size is 5MB' },
        { status: 400 }
      )
    }

    // Get current staff to check for existing photo
    const staff = await prisma.staff.findUnique({
      where: { id: session.user.id },
      select: { profilePhotoKey: true },
    })

    // Delete old photo if exists
    if (staff?.profilePhotoKey) {
      await storageService.deleteFile(staff.profilePhotoKey)
    }

    // Generate key and upload
    const key = storageService.generateKey(`staff-photos/${session.user.id}`, file.name)
    const buffer = Buffer.from(await file.arrayBuffer())

    const result = await storageService.uploadFile(key, buffer, file.type)

    if (!result.success) {
      return NextResponse.json(
        { error: result.error || 'Failed to upload photo' },
        { status: 500 }
      )
    }

    // Update staff record
    await prisma.staff.update({
      where: { id: session.user.id },
      data: { profilePhotoKey: key },
    })

    // Get public URL
    const photoUrl = await storageService.getPublicUrl(key)

    return NextResponse.json({
      success: true,
      message: 'Profile photo uploaded successfully',
      profilePhotoKey: key,
      profilePhotoUrl: photoUrl,
    })
  } catch (error) {
    if (typeof error === 'object' && error !== null && 'status' in error) {
      const err = error as { status: number; message: string }
      return NextResponse.json({ error: err.message }, { status: err.status })
    }
    console.error('Error uploading profile photo:', error)
    return NextResponse.json({ error: 'Failed to upload profile photo' }, { status: 500 })
  }
}

/**
 * DELETE /api/v1/profile/photo
 * Delete profile photo
 */
export async function DELETE() {
  try {
    const session = await requireStaffSession()

    // Get current staff
    const staff = await prisma.staff.findUnique({
      where: { id: session.user.id },
      select: { profilePhotoKey: true },
    })

    if (!staff?.profilePhotoKey) {
      return NextResponse.json({ error: 'No profile photo to delete' }, { status: 400 })
    }

    // Delete from storage
    const isConfigured = await storageService.isConfigured()
    if (isConfigured) {
      await storageService.deleteFile(staff.profilePhotoKey)
    }

    // Clear from database
    await prisma.staff.update({
      where: { id: session.user.id },
      data: { profilePhotoKey: null },
    })

    return NextResponse.json({
      success: true,
      message: 'Profile photo deleted successfully',
    })
  } catch (error) {
    if (typeof error === 'object' && error !== null && 'status' in error) {
      const err = error as { status: number; message: string }
      return NextResponse.json({ error: err.message }, { status: err.status })
    }
    console.error('Error deleting profile photo:', error)
    return NextResponse.json({ error: 'Failed to delete profile photo' }, { status: 500 })
  }
}
