import { NextRequest, NextResponse } from 'next/server';
import { db, schema } from '@/lib/db';
import { eq } from 'drizzle-orm';
import { updateFinancialDataSchema } from '@/lib/validators';
import { getSession } from '@/lib/auth';
import { isCompanyOwner, updateCompanyFinancialData, getCompanyById } from '@/lib/companies';

/**
 * GET /api/companies/[id]/financial
 * Get company financial data
 * - Owner only: can view financial data and payment method
 */
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;

    // Verify authentication
    const accessToken = request.cookies.get('scriba.access_token')?.value;
    const sessionData = await getSession(accessToken);

    if (!sessionData) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const { user } = sessionData;

    // Verify user belongs to this company
    if (user.companyId !== id) {
      return NextResponse.json(
        { error: 'Access denied. You are not a member of this company.' },
        { status: 403 }
      );
    }

    // Verify ownership - only owner can view financial data
    const isOwner = await isCompanyOwner(user.id, id);
    if (!isOwner) {
      return NextResponse.json(
        { error: 'Only the company owner can view financial data' },
        { status: 403 }
      );
    }

    // Get company
    const company = await getCompanyById(id);
    if (!company) {
      return NextResponse.json({ error: 'Company not found' }, { status: 404 });
    }

    return NextResponse.json({
      financialData: company.financialData || {},
      stripeCustomerId: company.stripeCustomerId,
    });

  } catch (error) {
    console.error('Get financial data error:', error);
    return NextResponse.json(
      { error: 'Failed to retrieve financial data' },
      { status: 500 }
    );
  }
}

/**
 * PATCH /api/companies/[id]/financial
 * Update company financial data
 * - Owner only: can edit financial data
 */
export async function PATCH(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;

    // Verify authentication
    const accessToken = request.cookies.get('scriba.access_token')?.value;
    const sessionData = await getSession(accessToken);

    if (!sessionData) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const { user } = sessionData;

    // Verify ownership
    const isOwner = await isCompanyOwner(user.id, id);
    if (!isOwner) {
      return NextResponse.json(
        { error: 'Only the company owner can edit financial data' },
        { status: 403 }
      );
    }

    // Parse and validate request body
    const body = await request.json();
    const parsed = updateFinancialDataSchema.safeParse(body);

    if (!parsed.success) {
      return NextResponse.json(
        { error: parsed.error.issues[0]?.message ?? 'Invalid input' },
        { status: 400 }
      );
    }

    // Update financial data
    const updated = await updateCompanyFinancialData(id, parsed.data);

    if (!updated) {
      return NextResponse.json(
        { error: 'Company not found' },
        { status: 404 }
      );
    }

    return NextResponse.json({
      success: true,
      financialData: updated.financialData,
      message: 'Financial data updated successfully',
    });

  } catch (error) {
    console.error('Update financial data error:', error);
    return NextResponse.json(
      { error: 'Failed to update financial data' },
      { status: 500 }
    );
  }
}
