import { NextRequest, NextResponse } from 'next/server';
import { db, schema } from '@/lib/db';
import { eq } from 'drizzle-orm';
import { getSession } from '@/lib/auth';
import { addTokensToCompany } from '@/lib/companies';
import { z } from 'zod';

const assignTokensSchema = z.object({
  tokens: z.number().int().positive('Token amount must be a positive integer'),
});

/**
 * POST /api/admin/companies/[id]/tokens
 * Assign free tokens to a company (admin only)
 */
export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id: companyId } = await params;

    // Authenticate user
    const accessToken = request.cookies.get('scriba.access_token')?.value;
    const session = await getSession(accessToken);
    if (!session) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    // Verify admin role
    const currentUser = await db.query.users.findFirst({
      where: eq(schema.users.id, session.user.id),
    });
    if (!currentUser || currentUser.role !== 'admin') {
      return NextResponse.json({ error: 'Forbidden - Admin access required' }, { status: 403 });
    }

    // Validate request body
    let body;
    try {
      body = await request.json();
    } catch {
      return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
    }

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

    const { tokens } = parsed.data;

    // Add tokens to company
    const result = await addTokensToCompany(companyId, tokens);

    if (!result.success) {
      return NextResponse.json({ error: result.error }, { status: 400 });
    }

    return NextResponse.json({
      success: true,
      message: `${tokens.toLocaleString()} tokens assigned to company`,
      companyId,
      tokensAdded: tokens,
      newBalance: result.newBalance,
    });
  } catch (error) {
    console.error('Assign tokens error:', error);
    return NextResponse.json({ error: 'Failed to assign tokens' }, { status: 500 });
  }
}
