using FluentValidation;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Meezi.API.Models.Hr;
using Meezi.API.Services;
using Meezi.Core.Enums;
using Meezi.Core.Interfaces;
using Meezi.Core.Utilities;
using Meezi.Infrastructure.Data;
using Meezi.Shared;

namespace Meezi.API.Controllers;

[Route("api/cafes/{cafeId}")]
public class HrController : CafeApiControllerBase
{
    private readonly IHrService _hr;
    private readonly IValidator<CreateLeaveRequest> _leaveValidator;
    private readonly IValidator<ReviewLeaveRequest> _reviewValidator;
    private readonly IValidator<CreateSalaryRequest> _salaryValidator;
    private readonly AppDbContext _db;

    public HrController(
        IHrService hr,
        IValidator<CreateLeaveRequest> leaveValidator,
        IValidator<ReviewLeaveRequest> reviewValidator,
        IValidator<CreateSalaryRequest> salaryValidator,
        AppDbContext db)
    {
        _hr = hr;
        _leaveValidator = leaveValidator;
        _reviewValidator = reviewValidator;
        _salaryValidator = salaryValidator;
        _db = db;
    }

    [HttpGet("employees")]
    public async Task<IActionResult> GetEmployees(
        string cafeId,
        ITenantContext tenant,
        [FromQuery] string? branchId = null,
        CancellationToken ct = default)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        var data = await _hr.GetEmployeesAsync(cafeId, branchId, ct);
        return Ok(new ApiResponse<IReadOnlyList<EmployeeSummaryDto>>(true, data));
    }

    [HttpGet("employees/{employeeId}")]
    public async Task<IActionResult> GetEmployee(string cafeId, string employeeId, ITenantContext tenant, CancellationToken ct)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        var data = await _hr.GetEmployeeAsync(cafeId, employeeId, ct);
        if (data is null) return NotFoundError();
        return Ok(new ApiResponse<EmployeeSummaryDto>(true, data));
    }

    [HttpGet("employees/{employeeId}/shift/today")]
    public async Task<IActionResult> GetTodayShift(string cafeId, string employeeId, ITenantContext tenant, CancellationToken ct)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        if (EnsureSelfOrManager(employeeId, tenant) is { } forbidden) return forbidden;
        var data = await _hr.GetTodayShiftAsync(cafeId, employeeId, ct);
        if (data is null) return NotFoundError();
        return Ok(new ApiResponse<TodayShiftDto>(true, data));
    }

    [HttpPost("employees/{employeeId}/attendance/clock-in")]
    public async Task<IActionResult> ClockIn(string cafeId, string employeeId, ITenantContext tenant, CancellationToken ct)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        if (EnsureSelfOrManager(employeeId, tenant) is { } forbidden) return forbidden;
        var data = await _hr.ClockInAsync(cafeId, employeeId, ct);
        if (data is null) return NotFoundError();
        return Ok(new ApiResponse<AttendanceDto>(true, data));
    }

    [HttpPost("employees/{employeeId}/attendance/clock-out")]
    public async Task<IActionResult> ClockOut(string cafeId, string employeeId, ITenantContext tenant, CancellationToken ct)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        if (EnsureSelfOrManager(employeeId, tenant) is { } forbidden) return forbidden;
        var data = await _hr.ClockOutAsync(cafeId, employeeId, ct);
        if (data is null) return BadRequest(new ApiResponse<object>(false, null, new ApiError("INVALID", "Clock-in required before clock-out.")));
        return Ok(new ApiResponse<AttendanceDto>(true, data));
    }

    [HttpGet("attendance")]
    public async Task<IActionResult> GetAttendance(
        string cafeId,
        [FromQuery] string? employeeId,
        [FromQuery] DateOnly? from,
        [FromQuery] DateOnly? to,
        ITenantContext tenant,
        CancellationToken ct)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        var data = await _hr.GetAttendanceAsync(cafeId, employeeId, from, to, ct);
        return Ok(new ApiResponse<IReadOnlyList<AttendanceDto>>(true, data));
    }

    [HttpGet("employees/{employeeId}/shifts")]
    public async Task<IActionResult> GetShifts(string cafeId, string employeeId, ITenantContext tenant, CancellationToken ct)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        var data = await _hr.GetShiftsAsync(cafeId, employeeId, ct);
        return Ok(new ApiResponse<IReadOnlyList<ShiftDto>>(true, data));
    }

    [HttpPut("employees/{employeeId}/shifts")]
    public async Task<IActionResult> UpsertShifts(
        string cafeId,
        string employeeId,
        [FromBody] UpsertShiftsRequest request,
        ITenantContext tenant,
        CancellationToken ct)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        if (EnsureManager(tenant) is { } forbidden) return forbidden;
        var data = await _hr.UpsertShiftsAsync(cafeId, employeeId, request, ct);
        return Ok(new ApiResponse<IReadOnlyList<ShiftDto>>(true, data));
    }

    [HttpGet("leave-requests")]
    public async Task<IActionResult> GetLeaveRequests(
        string cafeId,
        [FromQuery] LeaveStatus? status,
        ITenantContext tenant,
        CancellationToken ct)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        var data = await _hr.GetLeaveRequestsAsync(cafeId, status, ct);
        return Ok(new ApiResponse<IReadOnlyList<LeaveRequestDto>>(true, data));
    }

    [HttpPost("employees/{employeeId}/leave-requests")]
    public async Task<IActionResult> CreateLeave(
        string cafeId,
        string employeeId,
        [FromBody] CreateLeaveRequest request,
        ITenantContext tenant,
        CancellationToken ct)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        if (EnsureSelfOrManager(employeeId, tenant) is { } forbidden) return forbidden;
        var validation = await _leaveValidator.ValidateAsync(request, ct);
        if (!validation.IsValid) return BadRequest(ValidationError(validation));

        var data = await _hr.CreateLeaveRequestAsync(cafeId, employeeId, request, ct);
        if (data is null) return NotFoundError();
        return Ok(new ApiResponse<LeaveRequestDto>(true, data));
    }

    [HttpPatch("leave-requests/{leaveId}/status")]
    public async Task<IActionResult> ReviewLeave(
        string cafeId,
        string leaveId,
        [FromBody] ReviewLeaveRequest request,
        ITenantContext tenant,
        CancellationToken ct)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        if (EnsureManager(tenant) is { } forbidden) return forbidden;
        var validation = await _reviewValidator.ValidateAsync(request, ct);
        if (!validation.IsValid) return BadRequest(ValidationError(validation));

        var data = await _hr.ReviewLeaveRequestAsync(cafeId, leaveId, tenant.UserId!, request, ct);
        if (data is null) return NotFoundError();
        return Ok(new ApiResponse<LeaveRequestDto>(true, data));
    }

    [HttpGet("salaries")]
    public async Task<IActionResult> GetSalaries(
        string cafeId,
        [FromQuery] string? monthYear,
        ITenantContext tenant,
        CancellationToken ct)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        var data = await _hr.GetSalariesAsync(cafeId, monthYear, ct);
        return Ok(new ApiResponse<IReadOnlyList<EmployeeSalaryDto>>(true, data));
    }

    [HttpPost("salaries")]
    public async Task<IActionResult> CreateSalary(
        string cafeId,
        [FromBody] CreateSalaryRequest request,
        ITenantContext tenant,
        CancellationToken ct)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        if (EnsureManager(tenant) is { } forbidden) return forbidden;
        var validation = await _salaryValidator.ValidateAsync(request, ct);
        if (!validation.IsValid) return BadRequest(ValidationError(validation));

        var data = await _hr.CreateSalaryAsync(cafeId, request, ct);
        if (data is null) return NotFoundError();
        return Ok(new ApiResponse<EmployeeSalaryDto>(true, data));
    }

    [HttpPatch("salaries/{salaryId}/paid")]
    public async Task<IActionResult> MarkPaid(string cafeId, string salaryId, ITenantContext tenant, CancellationToken ct)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        if (EnsureManager(tenant) is { } forbidden) return forbidden;
        var data = await _hr.MarkSalaryPaidAsync(cafeId, salaryId, ct);
        if (data is null) return NotFoundError();
        return Ok(new ApiResponse<EmployeeSalaryDto>(true, data));
    }

    /// <summary>Set or update username/password credentials for an employee. Owner/Manager only.</summary>
    [HttpPut("employees/{employeeId}/credentials")]
    public async Task<IActionResult> SetCredentials(
        string cafeId,
        string employeeId,
        [FromBody] SetEmployeeCredentialsRequest request,
        ITenantContext tenant,
        CancellationToken ct)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        if (EnsureManager(tenant) is { } forbidden) return forbidden;

        var username = request.Username.Trim().ToLowerInvariant();

        if (string.IsNullOrWhiteSpace(username))
            return BadRequest(new ApiResponse<object>(false, null, new ApiError("VALIDATION_ERROR", "Username is required.", "Username")));

        if (request.Password.Length < 8)
            return BadRequest(new ApiResponse<object>(false, null, new ApiError("VALIDATION_ERROR", "Password must be at least 8 characters.", "Password")));

        var employee = await _db.Employees
            .FirstOrDefaultAsync(e => e.Id == employeeId && e.CafeId == cafeId && e.DeletedAt == null, ct);

        if (employee is null) return NotFoundError();

        // Check username uniqueness within the cafe (excluding the employee itself)
        var conflict = await _db.Employees
            .AnyAsync(e => e.CafeId == cafeId && e.Id != employeeId && e.DeletedAt == null
                        && e.Username != null && e.Username.ToLower() == username, ct);
        if (conflict)
            return Conflict(new ApiResponse<object>(false, null, new ApiError("USERNAME_TAKEN", "This username is already in use by another employee.")));

        employee.Username = username;
        employee.PasswordHash = PasswordHasher.Hash(request.Password);
        await _db.SaveChangesAsync(ct);

        return Ok(new ApiResponse<object>(true, null));
    }

    /// <summary>Remove username/password credentials from an employee. Owner/Manager only.</summary>
    [HttpDelete("employees/{employeeId}/credentials")]
    public async Task<IActionResult> RemoveCredentials(
        string cafeId,
        string employeeId,
        ITenantContext tenant,
        CancellationToken ct)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        if (EnsureManager(tenant) is { } forbidden) return forbidden;

        var employee = await _db.Employees
            .FirstOrDefaultAsync(e => e.Id == employeeId && e.CafeId == cafeId && e.DeletedAt == null, ct);

        if (employee is null) return NotFoundError();

        employee.Username = null;
        employee.PasswordHash = null;
        await _db.SaveChangesAsync(ct);

        return Ok(new ApiResponse<object>(true, null));
    }
}
