import { NextRequest, NextResponse } from 'next/server' import { supabaseAdmin } from '@/lib/supabase/admin' /** * @description Retrieves paginated list of daily closing reports with optional filtering by location, date range, and status * @param {NextRequest} request - HTTP request with query parameters: location_id, start_date, end_date, status, limit (default 50), offset (default 0) * @returns {NextResponse} JSON with success status, array of closing reports, and pagination metadata * @example GET /api/aperture/finance/daily-closing?location_id=...&start_date=2026-01-01&end_date=2026-01-31&status=completed * @audit BUSINESS RULE: Daily closing reports contain financial reconciliation data for each business day * @audit SECURITY: Requires authenticated admin/manager role via RLS policies * @audit Validate: Supports filtering by report status (pending, completed, reconciled) * @audit PERFORMANCE: Uses indexed queries on report_date and location_id * @audit AUDIT: Daily closing reports are immutable financial records for compliance */ export async function GET(request: NextRequest) { try { const searchParams = request.nextUrl.searchParams const location_id = searchParams.get('location_id') const start_date = searchParams.get('start_date') const end_date = searchParams.get('end_date') const status = searchParams.get('status') const limit = parseInt(searchParams.get('limit') || '50') const offset = parseInt(searchParams.get('offset') || '0') let query = supabaseAdmin .from('daily_closing_reports') .select('*', { count: 'exact' }) .order('report_date', { ascending: false }) .range(offset, offset + limit - 1) if (location_id) { query = query.eq('location_id', location_id) } if (status) { query = query.eq('status', status) } if (start_date) { query = query.gte('report_date', start_date) } if (end_date) { query = query.lte('report_date', end_date) } const { data: reports, error, count } = await query if (error) { console.error('Error fetching daily closing reports:', error) return NextResponse.json( { success: false, error: 'Failed to fetch daily closing reports' }, { status: 500 } ) } return NextResponse.json({ success: true, data: reports || [], pagination: { total: count || 0, limit, offset, hasMore: (count || 0) > offset + limit } }) } catch (error) { console.error('Error in GET /api/aperture/finance/daily-closing:', error) return NextResponse.json( { success: false, error: 'Internal server error' }, { status: 500 } ) } }