import { NextRequest, NextResponse } from 'next/server';
import prisma from '@/lib/db';
import bcrypt from 'bcryptjs';
import { withPermission, isErrorResponse } from '@/lib/auth/api-guard';

export const dynamic = 'force-dynamic';

// GET - List users
export async function GET(request: NextRequest) {
  const auth = await withPermission(request, { resource: 'settings', action: 'read' });
  if (isErrorResponse(auth)) return auth;

  try {
    const users = await prisma.gfsUser.findMany({
      select: {
        id: true,
        email: true,
        name: true,
        status: true,
        department: true,
        title: true,
        avatar: true,
        mfaEnabled: true,
        lastLogin: true,
        createdAt: true,
        roles: {
          include: {
            role: {
              select: { id: true, name: true, displayName: true },
            },
          },
        },
      },
      orderBy: { name: 'asc' },
    });

    return NextResponse.json({
      success: true,
      users: users.map((u: any) => ({
        ...u,
        roles: u.roles.map((r: any) => r.role),
      })),
    });
  } catch (error) {
    console.error('Users GET error:', error);
    return NextResponse.json({ success: false, error: 'Failed to fetch users' }, { status: 500 });
  }
}

// POST - Create user
export async function POST(request: NextRequest) {
  const auth = await withPermission(request, { resource: 'settings', action: 'admin' });
  if (isErrorResponse(auth)) return auth;

  try {
    const body = await request.json();
    const { email, name, password, department, title, roleIds } = body;

    if (!email || !password) {
      return NextResponse.json({ success: false, error: 'Email and password required' }, { status: 400 });
    }

    // Check if user exists
    const existing = await prisma.gfsUser.findUnique({ where: { email: email.toLowerCase() } });
    if (existing) {
      return NextResponse.json({ success: false, error: 'User already exists' }, { status: 400 });
    }

    const passwordHash = await bcrypt.hash(password, 12);

    const user = await prisma.gfsUser.create({
      data: {
        email: email.toLowerCase(),
        name,
        passwordHash,
        department,
        title,
        status: 'active',
      },
    });

    // Assign roles
    if (roleIds && roleIds.length > 0) {
      await prisma.userRole.createMany({
        data: roleIds.map((roleId: string) => ({
          userId: user.id,
          roleId,
          scope: 'global',
        })),
      });
    } else {
      // Assign default employee role
      const defaultRole = await prisma.role.findFirst({ where: { isDefault: true } });
      if (defaultRole) {
        await prisma.userRole.create({
          data: {
            userId: user.id,
            roleId: defaultRole.id,
            scope: 'global',
          },
        });
      }
    }

    // Log audit event
    await prisma.auditLog.create({
      data: {
        userId: auth.userId,
        action: 'create_user',
        resource: 'user',
        resourceId: user.id,
        details: { email: user.email, createdBy: auth.email },
        success: true,
      },
    });

    return NextResponse.json({
      success: true,
      user: {
        id: user.id,
        email: user.email,
        name: user.name,
        department: user.department,
        title: user.title,
      },
    });
  } catch (error) {
    console.error('Users POST error:', error);
    return NextResponse.json({ success: false, error: 'Failed to create user' }, { status: 500 });
  }
}
