import { NextRequest, NextResponse } from 'next/server'
import { getSessionUser } from '@/lib/auth'
import { createAdminClient } from '@/lib/supabase/admin'
import { getCompanyContext, logCompanyEvent } from '@/lib/data/companies'
import { canManageCompany } from '@/lib/domain/company'

export const runtime = 'nodejs'

const MAX_BYTES = 2 * 1024 * 1024
const TYPES: Record<string, string> = {
  'image/png': 'png',
  'image/jpeg': 'jpg',
  'image/svg+xml': 'svg',
}

/** Company logo upload (Task 91) — Nash: "maybe they want to add a logo". */
export async function POST(req: NextRequest) {
  const user = await getSessionUser()
  if (!user) return NextResponse.json({ error: 'Sign in first.' }, { status: 401 })
  const ctx = await getCompanyContext(user.id)
  if (!ctx.available) {
    return NextResponse.json({ error: 'Company verification needs database migration 0013.' }, { status: 503 })
  }
  if (!ctx.company || ctx.membership?.status !== 'approved' || !canManageCompany(ctx.membership.role)) {
    return NextResponse.json({ error: 'Only a Company Owner or Company Admin can change the logo.' }, { status: 403 })
  }

  const form = await req.formData()
  const file = form.get('file')
  if (!(file instanceof File)) return NextResponse.json({ error: 'No file.' }, { status: 400 })
  if (file.size > MAX_BYTES) return NextResponse.json({ error: 'Logo must be 2 MB or smaller.' }, { status: 413 })
  const ext = TYPES[file.type]
  if (!ext) return NextResponse.json({ error: 'Use a PNG, JPG or SVG.' }, { status: 415 })

  const admin = createAdminClient()
  const path = `${ctx.company.id}/logo-${Date.now()}.${ext}`
  const { error: uploadError } = await admin.storage
    .from('company-logos')
    .upload(path, Buffer.from(await file.arrayBuffer()), { contentType: file.type, upsert: true })
  if (uploadError) {
    return NextResponse.json(
      { error: `Could not store the logo (${uploadError.message}). Is the company-logos bucket created by migration 0013?` },
      { status: 500 },
    )
  }
  const { data: pub } = admin.storage.from('company-logos').getPublicUrl(path)
  const logoUrl = pub.publicUrl
  await admin.from('companies').update({ logo_url: logoUrl, updated_at: new Date().toISOString() }).eq('id', ctx.company.id)
  await logCompanyEvent({
    companyId: ctx.company.id,
    actorUserId: user.id,
    actorLabel: user.name || user.email,
    eventType: 'logo_updated',
    oldValue: { logo_url: ctx.company.logo_url },
    newValue: { logo_url: logoUrl },
  })
  return NextResponse.json({ ok: true, logo_url: logoUrl })
}
