import { beforeEach, describe, expect, it, vi } from 'vitest'
import { NextRequest, NextResponse } from 'next/server'
import { createFakeSupabase } from './stubs/fake-supabase'

const db = createFakeSupabase()
const mocks = vi.hoisted(() => ({
  guard: vi.fn(), rpc: vi.fn(), logTripEvent: vi.fn(async () => {}),
}))
vi.mock('@/lib/supabase/admin', () => ({ createAdminClient: () => ({ from: db.from.bind(db), rpc: mocks.rpc }) }))
vi.mock('@/lib/api-guard', () => ({ requireParticipant: mocks.guard }))
vi.mock('@/lib/audit', () => ({ logTripEvent: mocks.logTripEvent }))

const { POST } = await import('@/app/api/trips/[id]/permits/[permitId]/processing/route')
const tripId = '378644e1-6503-4c5e-9149-41749dd6a006'
const permitId = 'b2979816-271f-4de2-9acb-57147e16c0a1'

function action(value: unknown) {
  return POST(new NextRequest('https://workspace.test/api/trips/x/permits/y/processing', {
    method: 'POST', body: JSON.stringify({ action: value }),
  }), { params: Promise.resolve({ id: tripId, permitId }) })
}

beforeEach(() => {
  db.reset()
  vi.clearAllMocks()
  db.seed('trips', [{ id: tripId, source_system: 'workspace' }])
  db.seed('permits', [{ id: permitId, trip_id: tripId, source_system: null, extraction_status: 'pending' }])
  mocks.guard.mockResolvedValue({ ok: true,
    user: { id: 'user-id', email: 'broker@example.test' }, participant: { role: 'broker', name: 'Broker' } })
  mocks.rpc.mockResolvedValue({ data: true, error: null })
})

describe('Workspace permit processing controls', () => {
  it('cancels one authorized Workspace permit without syncing GPT', async () => {
    expect((await action('cancel')).status).toBe(200)
    expect(mocks.rpc).toHaveBeenCalledWith('cancel_workspace_permit', { p_permit_id: permitId })
    expect(mocks.logTripEvent).toHaveBeenCalledWith(expect.objectContaining({ sync: false, action: 'permit_processing_cancelled' }))
  })

  it('requeues a failed Workspace permit', async () => {
    expect((await action('retry')).status).toBe(200)
    expect(mocks.rpc).toHaveBeenCalledWith('retry_workspace_permit', { p_permit_id: permitId })
  })

  it('does not manage Synchron permits', async () => {
    db.table('permits')[0].source_system = 'synchron'
    expect((await action('cancel')).status).toBe(403)
    expect(mocks.rpc).not.toHaveBeenCalled()
  })

  it('does not manage permits on an imported Synchron trip', async () => {
    db.table('trips')[0].source_system = 'synchron'
    expect((await action('retry')).status).toBe(403)
    expect(mocks.rpc).not.toHaveBeenCalled()
  })

  it('rejects a stale action when the job already changed', async () => {
    mocks.rpc.mockResolvedValue({ data: false, error: null })
    expect((await action('cancel')).status).toBe(409)
    expect(mocks.logTripEvent).not.toHaveBeenCalled()
  })

  it('rejects someone who cannot upload files', async () => {
    mocks.guard.mockResolvedValue({ ok: true,
      user: { id: 'user-id', email: 'shipper@example.test' }, participant: { role: 'shipper', name: 'Shipper' } })
    expect((await action('retry')).status).toBe(403)
    expect(mocks.rpc).not.toHaveBeenCalled()
  })

  it('requires a participant and a valid action', async () => {
    mocks.guard.mockResolvedValueOnce({ ok: false, response: NextResponse.json({ error: 'Sign in first.' }, { status: 401 }) })
    expect((await action('cancel')).status).toBe(401)
    expect((await action('unknown')).status).toBe(400)
    expect(mocks.rpc).not.toHaveBeenCalled()
  })
})
