using System.Security.Claims;
using FastEndpoints;
using FluentValidation;
using Microsoft.EntityFrameworkCore;
using TrackQrApi.Data;
using TrackQrApi.Features.Auth.Common;

namespace TrackQrApi.Features.Auth.Endpoints;

public class DeleteAccountRequest
{
    public string Password { get; set; } = string.Empty;
}

public class DeleteAccountValidator : Validator<DeleteAccountRequest>
{
    public DeleteAccountValidator()
    {
        RuleFor(x => x.Password)
            .NotEmpty().WithMessage("Password is required to delete account");
    }
}

public class DeleteAccountEndpoint(AppDbContext db) : Endpoint<DeleteAccountRequest>
{
    public override void Configure()
    {
        Delete("/auth/account");
    }

    public override async Task HandleAsync(DeleteAccountRequest req, CancellationToken ct)
    {
        var userId = Guid.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);

        var user = await db.Users.FindAsync([userId], ct);
        if (user == null)
        {
            await HttpContext.Response.SendAsync(new MessageResponse("User not found"), 404, cancellation: ct);
            return;
        }

        // Verify password
        if (!BCrypt.Net.BCrypt.Verify(req.Password, user.PasswordHash))
        {
            await HttpContext.Response.SendAsync(new MessageResponse("Password is incorrect"), 400, cancellation: ct);
            return;
        }

        // Delete all user's workspaces (cascade will handle related data)
        var workspaces = await db.Workspaces.Where(w => w.OwnerUserId == userId).ToListAsync(ct);
        db.Workspaces.RemoveRange(workspaces);

        // Delete user
        db.Users.Remove(user);
        await db.SaveChangesAsync(ct);

        await HttpContext.Response.SendAsync(new MessageResponse("Account deleted successfully"), cancellation: ct);
    }
}