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'
import { getSignedS3Url, S3_PREFIX, uploadFileToS3 } from '@/lib/storage/s3'

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 })

  let stored
  try {
    stored = await uploadFileToS3(file, `logo-${ctx.company.id}-${Date.now()}.${ext}`, S3_PREFIX.companyLogo)
  } catch (error) {
    console.error('S3 logo upload failed:', error instanceof Error ? error.message : error)
    return NextResponse.json(
      { error: 'Could not store the logo.' },
      { status: 500 },
    )
  }
  const admin = createAdminClient()
  const logoUrl = stored.url
  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: await getSignedS3Url(stored.key) })
}
