import { NextRequest, NextResponse } from 'next/server';
import { withAuth } from '@/lib/api-guards';
import { hashPassword } from '@/lib/auth';
import { createAuditLog } from '@/lib/audit-logger';

// GET: Fetch all users in user's scope (restricted to ADMIN and DIRECTOR)
export const GET = withAuth(async (req, { prisma }) => {
  try {
    const users = await prisma.user.findMany({
      select: {
        id: true,
        username: true,
        email: true,
        role: true,
        hotelId: true,
        area: true,
        status: true,
        hotel: {
          select: {
            name: true,
            code: true,
          }
        }
      },
      orderBy: { username: 'asc' }
    });

    return NextResponse.json({ users });
  } catch (err: any) {
    console.error('Failed to fetch users:', err);
    return NextResponse.json({ error: 'Failed to fetch users' }, { status: 500 });
  }
}, ['admin', 'director']);

// POST: Add new user account (restricted to ADMIN)
export const POST = withAuth(async (req, { session, prisma }) => {
  try {
    const body = await req.json();
    const { username, email, password, role, hotelId, area, status } = body;

    if (!username || !email || !password || !role || !hotelId || !area) {
      return NextResponse.json(
        { error: 'username, email, password, role, hotelId y area son campos obligatorios.' },
        { status: 400 }
      );
    }

    const passwordHash = await hashPassword(password);

    const newUser = await prisma.$transaction(async (tx: any) => {
      // 1. Create the user
      const user = await tx.user.create({
        data: {
          username,
          email,
          passwordHash,
          role,
          hotelId: parseInt(hotelId),
          area,
          status: status || 'ACTIVE'
        }
      });

      // 2. Log audit trail
      await createAuditLog(tx, {
        userId: session.userId,
        action: 'CREATE',
        targetTable: 'users',
        targetId: user.id,
        newValue: user,
        ipAddress: req.headers.get('x-forwarded-for') || '127.0.0.1'
      });

      return user;
    });

    // Strip passwordHash from response for security
    const { passwordHash: _, ...userWithoutPassword } = newUser;

    return NextResponse.json({ user: userWithoutPassword }, { status: 201 });
  } catch (err: any) {
    console.error('Failed to create user:', err);
    if (err.code === 'P2002') {
      return NextResponse.json({ error: 'El nombre de usuario o correo ya está registrado.' }, { status: 400 });
    }
    return NextResponse.json({ error: 'Failed to create user' }, { status: 500 });
  }
}, ['admin']);
