using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SIGCM.Application.DTOs;
using SIGCM.Domain.Entities;
using SIGCM.Domain.Interfaces;
using SIGCM.Infrastructure.Repositories;

namespace SIGCM.API.Controllers;

[ApiController]
[Route("api/[controller]")]
[Authorize(Roles = "Admin")]
public class UsersController : ControllerBase
{
    private readonly IUserRepository _repository;
    private readonly AuditRepository _auditRepo;

    public UsersController(IUserRepository repository, AuditRepository auditRepo)
    {
        _repository = repository;
        _auditRepo = auditRepo;
    }

    [HttpGet]
    public async Task<IActionResult> GetAll()
    {
        var users = await _repository.GetAllAsync();
        // Excluimos clientes para que solo aparezcan en su propio gestor
        var sanitized = users
            .Where(u => u.Role != "Client")
            .Select(u => new { 
            u.Id, u.Username, u.Role, u.Email, u.CreatedAt 
        });
        return Ok(sanitized);
    }

    [HttpGet("{id}")]
    public async Task<IActionResult> GetById(int id)
    {
        var user = await _repository.GetByIdAsync(id);
        if (user == null) return NotFound();
        
        return Ok(new { user.Id, user.Username, user.Role, user.Email, user.CreatedAt });
    }

    [HttpPost]
    public async Task<IActionResult> Create(CreateUserDto dto)
    {
        // Check if exists
        var existing = await _repository.GetByUsernameAsync(dto.Username);
        if (existing != null) return BadRequest("El nombre de usuario ya existe.");

        var passwordHash = BCrypt.Net.BCrypt.HashPassword(dto.Password);
        
        var user = new User
        {
            Username = dto.Username,
            PasswordHash = passwordHash,
            Role = dto.Role,
            Email = dto.Email,
            CreatedAt = DateTime.UtcNow
        };

        var id = await _repository.CreateAsync(user);

        // Audit Log
        var currentUserIdStr = User.FindFirst("Id")?.Value;
        if (int.TryParse(currentUserIdStr, out int currentUserId))
        {
            await _auditRepo.AddLogAsync(new AuditLog
            {
                UserId = currentUserId,
                Action = "CREATE_USER",
                EntityId = id,
                EntityType = "User",
                Details = $"Usuario {dto.Username} creado con rol {dto.Role}",
                CreatedAt = DateTime.UtcNow
            });
        }

        return CreatedAtAction(nameof(GetById), new { id }, new { id, user.Username });
    }

    [HttpPut("{id}")]
    public async Task<IActionResult> Update(int id, UpdateUserDto dto)
    {
        var user = await _repository.GetByIdAsync(id);
        if (user == null) return NotFound();

        user.Username = dto.Username;
        user.Role = dto.Role;
        user.Email = dto.Email;

        if (!string.IsNullOrEmpty(dto.Password))
        {
            user.PasswordHash = BCrypt.Net.BCrypt.HashPassword(dto.Password);
        }

        await _repository.UpdateAsync(user);

        // Audit Log
        var currentUserIdStr = User.FindFirst("Id")?.Value;
        if (int.TryParse(currentUserIdStr, out int currentUserId))
        {
            await _auditRepo.AddLogAsync(new AuditLog
            {
                UserId = currentUserId,
                Action = "UPDATE_USER",
                EntityId = id,
                EntityType = "User",
                Details = $"Usuario {user.Username} actualizado (Rol: {user.Role})",
                CreatedAt = DateTime.UtcNow
            });
        }

        return NoContent();
    }

    [HttpDelete("{id}")]
    public async Task<IActionResult> Delete(int id)
    {
        // Safe check: prevent deleting yourself optional but good practice
        // For now simple delete
        await _repository.DeleteAsync(id);

        // Audit Log
        var currentUserIdStr = User.FindFirst("Id")?.Value;
        if (int.TryParse(currentUserIdStr, out int currentUserId))
        {
            await _auditRepo.AddLogAsync(new AuditLog
            {
                UserId = currentUserId,
                Action = "DELETE_USER",
                EntityId = id,
                EntityType = "User",
                Details = $"Usuario ID #{id} eliminado",
                CreatedAt = DateTime.UtcNow
            });
        }

        return NoContent();
    }
}
