import { NextRequest, NextResponse } from 'next/server'
import { DocumentType } from '@/lib/sdk/tom-generator/types'
import { evidenceStore } from '@/lib/sdk/tom-generator/evidence-store'

/**
 * TOM Generator Evidence API
 *
 * GET /api/sdk/v1/tom-generator/evidence?tenantId=xxx - List all evidence documents
 * DELETE /api/sdk/v1/tom-generator/evidence?tenantId=xxx&id=xxx - Delete evidence
 */

// =============================================================================
// HANDLERS
// =============================================================================

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const tenantId = searchParams.get('tenantId')
    const documentType = searchParams.get('type') as DocumentType | null
    const status = searchParams.get('status')
    const id = searchParams.get('id')

    if (!tenantId) {
      return NextResponse.json(
        { success: false, error: 'tenantId is required' },
        { status: 400 }
      )
    }

    // Get single document
    if (id) {
      const document = await evidenceStore.getById(tenantId, id)
      if (!document) {
        return NextResponse.json(
          { success: false, error: `Document not found: ${id}` },
          { status: 404 }
        )
      }
      return NextResponse.json({
        success: true,
        data: document,
      })
    }

    // Filter by type
    if (documentType) {
      const documents = await evidenceStore.getByType(tenantId, documentType)
      return NextResponse.json({
        success: true,
        data: documents,
        meta: {
          count: documents.length,
          filter: { type: documentType },
        },
      })
    }

    // Filter by status
    if (status) {
      const documents = await evidenceStore.getByStatus(tenantId, status)
      return NextResponse.json({
        success: true,
        data: documents,
        meta: {
          count: documents.length,
          filter: { status },
        },
      })
    }

    // Get all documents
    const documents = await evidenceStore.getAll(tenantId)

    // Group by type for summary
    const byType: Record<string, number> = {}
    const byStatus: Record<string, number> = {}
    documents.forEach((doc) => {
      byType[doc.documentType] = (byType[doc.documentType] || 0) + 1
      byStatus[doc.status] = (byStatus[doc.status] || 0) + 1
    })

    return NextResponse.json({
      success: true,
      data: documents,
      meta: {
        count: documents.length,
        byType,
        byStatus,
      },
    })
  } catch (error) {
    console.error('Failed to fetch evidence:', error)
    return NextResponse.json(
      { success: false, error: 'Failed to fetch evidence' },
      { status: 500 }
    )
  }
}

export async function DELETE(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const tenantId = searchParams.get('tenantId')
    const id = searchParams.get('id')

    if (!tenantId) {
      return NextResponse.json(
        { success: false, error: 'tenantId is required' },
        { status: 400 }
      )
    }

    if (!id) {
      return NextResponse.json(
        { success: false, error: 'id is required' },
        { status: 400 }
      )
    }

    const deleted = await evidenceStore.delete(tenantId, id)

    if (!deleted) {
      return NextResponse.json(
        { success: false, error: `Document not found: ${id}` },
        { status: 404 }
      )
    }

    return NextResponse.json({
      success: true,
      id,
      deletedAt: new Date().toISOString(),
    })
  } catch (error) {
    console.error('Failed to delete evidence:', error)
    return NextResponse.json(
      { success: false, error: 'Failed to delete evidence' },
      { status: 500 }
    )
  }
}

export async function OPTIONS() {
  return NextResponse.json(
    { status: 'ok' },
    {
      headers: {
        Allow: 'GET, DELETE, OPTIONS',
      },
    }
  )
}
