import { NextRequest, NextResponse } from 'next/server';
import { getSession } from '@/lib/auth';
import { db, schema } from '@/lib/db';
import { eq, desc } from 'drizzle-orm';
import { calculateCompanyMonthlyCharge } from '@/lib/billing-service';

/**
 * GET /api/billing/history
 * Returns past billing records + the current period estimate.
 */
export async function GET(request: NextRequest) {
  const accessToken = request.cookies.get('scriba.access_token')?.value;
  const session = await getSession(accessToken);
  if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  try {
    const records = await db.query.billingRecords.findMany({
      where: eq(schema.billingRecords.userId, session.user.id),
      orderBy: [desc(schema.billingRecords.periodStart)],
      limit: 24,
    });

    // Current period estimate (this month so far)
    const now = new Date();
    const periodStart = new Date(now.getFullYear(), now.getMonth(), 1);
    const periodEnd   = new Date(now.getFullYear(), now.getMonth() + 1, 1);
    const companyId = (session.user as any).companyId as string | null;
    const estimate = companyId
      ? await calculateCompanyMonthlyCharge(companyId, periodStart, periodEnd)
      : { totalTokens: 0, billableTokens: 0, freeTokensApplied: 0, amountCents: 0, slotChargesCents: 0 };

    return NextResponse.json({ records, estimate });
  } catch (err) {
    console.error('Billing history error:', err);
    return NextResponse.json({ error: 'Failed to fetch billing history' }, { status: 500 });
  }
}
