import { NextRequest, NextResponse } from 'next/server';
import { db, schema } from '@/lib/db';
import { eq, sql } from 'drizzle-orm';
import { createCompanySchema } from '@/lib/validators';
import { getSession } from '@/lib/auth';
import { getMaxUsersForPackage, initialLicenseCreditsForPackage } from '@/lib/companies';
import type { PackageTier } from '@/lib/companies';

/**
 * POST /api/companies
 * Create a new company. The authenticated user becomes the owner.
 * This is the entry point for new users - they must create a company first.
 */
export async function POST(request: NextRequest) {
  try {
    // 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;

    // Check if user already owns a company (one owner per user rule)
    const existingCompany = await db.query.companies.findFirst({
      where: eq(schema.companies.ownerId, user.id),
    });

    if (existingCompany) {
      return NextResponse.json(
        { error: 'You already own a company. Each user can only be the owner of one company.' },
        { status: 400 }
      );
    }

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

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

    const { name, package: packageTier, financialData, paymentMethod } = parsed.data;

    // Create company
    const companyId = crypto.randomUUID();
    const maxUsers = getMaxUsersForPackage(packageTier as PackageTier);

    // Start transaction
    const [company] = await db
      .insert(schema.companies)
      .values({
        id: companyId,
        name,
        package: packageTier,
        maxUsers,
        ownerId: user.id,
        financialData: financialData || {},
        paymentMethod: paymentMethod || null,
        licenseCreditsRemaining: initialLicenseCreditsForPackage(packageTier),
      })
      .returning();

    // Update the user to link them to the company and mark as owner
    await db
      .update(schema.users)
      .set({
        companyId: companyId,
        isOwner: true,
        updatedAt: new Date(),
      })
      .where(eq(schema.users.id, user.id));

    return NextResponse.json({
      success: true,
      company: {
        id: company.id,
        name: company.name,
        package: company.package,
        maxUsers: company.maxUsers,
        ownerId: company.ownerId,
        createdAt: company.createdAt,
      },
      message: 'Company created successfully. You are now the owner.',
    });

  } catch (error) {
    console.error('Create company error:', error);
    return NextResponse.json(
      { error: 'Failed to create company' },
      { status: 500 }
    );
  }
}

/**
 * GET /api/companies
 * Get the authenticated user's company
 * - Owner: full company data including financial
 * - Regular user: summary data only
 */
export async function GET(request: NextRequest) {
  try {
    // 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;

    // User must belong to a company
    if (!user.companyId) {
      return NextResponse.json(
        { error: 'No company associated with this user', code: 'NO_COMPANY' },
        { status: 400 }
      );
    }

    // Get company
    const company = await db.query.companies.findFirst({
      where: eq(schema.companies.id, user.companyId),
    });

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

    // Count users in company
    const userCountResult = await db
      .select({ count: sql<number>`count(*)` })
      .from(schema.users)
      .where(eq(schema.users.companyId, company.id));

    const count = userCountResult[0]?.count || 0;

    // Return different data based on owner status
    if (user.isOwner) {
      // Owner sees everything
      return NextResponse.json({
        company: {
          id: company.id,
          name: company.name,
          package: company.package,
          maxUsers: company.maxUsers,
          ownerId: company.ownerId,
          financialData: company.financialData,
          paymentMethod: company.paymentMethod,
          stripeCustomerId: company.stripeCustomerId,
          userCount: count,
          remainingSlots: company.maxUsers - count,
          createdAt: company.createdAt,
          updatedAt: company.updatedAt,
        },
        isOwner: true,
      });
    } else {
      // Non-owner sees limited data
      return NextResponse.json({
        company: {
          id: company.id,
          name: company.name,
          package: company.package,
          maxUsers: company.maxUsers,
          userCount: count,
          createdAt: company.createdAt,
        },
        isOwner: false,
      });
    }

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