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

// GET /api/admin/users - Get all users (admin only)
export async function GET(request: NextRequest) {
  try {
    const accessToken = request.cookies.get('scriba.access_token')?.value;
    const session = await getSession(accessToken);

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

    // Check if user is admin
    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 });
    }

    const users = await db.query.users.findMany({
      orderBy: [desc(schema.users.createdAt)]
    });
    const companies = await db.query.companies.findMany({
      columns: { id: true, package: true },
    });
    const companyPackageById = new Map(companies.map((company) => [company.id, company.package]));
    const usersWithEffectiveTier = users.map((user) => ({
      ...user,
      tier: (user.companyId ? companyPackageById.get(user.companyId) : null) ?? user.tier,
    }));

    return NextResponse.json({ users: usersWithEffectiveTier });
  } catch (error) {
    console.error('Error fetching users:', error);
    return NextResponse.json({ error: 'Failed to fetch users' }, { status: 500 });
  }
}

// POST /api/admin/users - Create new user (admin only)
// - Admins can be created without a company
// - Non-admin users (client) require a companyId
// - Owner flag can only be set to true when creating within a company context
export async function POST(request: NextRequest) {
  try {
    const accessToken = request.cookies.get('scriba.access_token')?.value;
    const session = await getSession(accessToken);

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

    // Check if user is admin
    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 });
    }

    const body = await request.json();
    const { email, name, role, password, companyId, isOwner } = body;

    // Validate required fields
    if (!email) {
      return NextResponse.json({ error: 'Email is required' }, { status: 400 });
    }

    // Non-admin users require a company
    if (role !== 'admin' && !companyId) {
      return NextResponse.json(
        { error: 'Company is required for non-admin users. Please create a company first or assign to an existing company.' },
        { status: 400 }
      );
    }

    // If companyId provided, verify company exists
    let companyPackage: string | null = null;
    if (companyId) {
      const company = await db.query.companies.findFirst({
        where: eq(schema.companies.id, companyId),
      });
      if (!company) {
        return NextResponse.json({ error: 'Company not found' }, { status: 404 });
      }
      companyPackage = company.package;

      // Check user limit for non-owners
      if (!isOwner) {
        const { canAddUserToCompany } = await import('@/lib/companies');
        const canAdd = await canAddUserToCompany(companyId);
        if (!canAdd.allowed) {
          return NextResponse.json({ error: canAdd.reason }, { status: 400 });
        }
      }
    }

    // Check if email already exists
    const existingUser = await db.query.users.findFirst({
      where: eq(schema.users.email, email)
    });

    if (existingUser) {
      return NextResponse.json({ error: 'Email already exists' }, { status: 400 });
    }

    // If creating as owner, ensure company exists and no other owner
    if (isOwner && companyId) {
      const company = await db.query.companies.findFirst({
        where: eq(schema.companies.id, companyId),
      });
      if (company && company.ownerId && company.ownerId !== 'pending') {
        return NextResponse.json(
          { error: 'Company already has an owner. Use the owner transfer endpoint instead.' },
          { status: 400 }
        );
      }
    }

    // Generate user ID
    const userId = crypto.randomUUID();
    const derivedTier = companyPackage ?? 'starter';

    // Create user
    const newUser = await db.insert(schema.users).values({
      id: userId,
      email,
      name: name || null,
      role: role || 'client',
      tier: derivedTier,
      companyId: companyId || null,
      isOwner: isOwner || false,
      emailVerified: true, // Admin-created users are pre-verified
    }).returning();

    // If this is an owner, update the company
    if (isOwner && companyId) {
      await db
        .update(schema.companies)
        .set({ ownerId: userId, updatedAt: new Date() })
        .where(eq(schema.companies.id, companyId));
    }

    // If password provided, create account with credential provider
    if (password) {
      const bcrypt = await import('bcrypt');
      const hashedPassword = await bcrypt.hash(password, 10);
      
      await db.insert(schema.accounts).values({
        id: crypto.randomUUID(),
        userId,
        accountId: email,
        providerId: 'credential',
        password: hashedPassword
      });
    }

    return NextResponse.json({ 
      success: true, 
      user: newUser[0],
      message: role === 'admin' 
        ? 'Admin user created successfully (no company required)'
        : `User created successfully${companyId ? ' and assigned to company' : ''}`,
    }, { status: 201 });
  } catch (error) {
    console.error('Error creating user:', error);
    return NextResponse.json({ error: 'Failed to create user' }, { status: 500 });
  }
}
