using Indotalent.Infrastructure.Database;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Indotalent.Features.Profile.PersonalInformation.Cqrs;

public class UpdateProfileRequest
{
    public string Id { get; set; } = string.Empty;
    public string? FirstName { get; set; }
    public string? LastName { get; set; }
    public string? ShortBio { get; set; }
    public string? JobTitle { get; set; }
    public DateTime? DateOfBirth { get; set; }
    public string? PhoneNumber { get; set; }
    public string? StreetAddress { get; set; }
    public string? City { get; set; }
    public string? Country { get; set; }
    public string? ZipCode { get; set; }
    public string? SocialMediaLinkedIn { get; set; }
    public string? SocialMediaInstagram { get; set; }
    public string? SocialMediaX { get; set; }
}

public class UpdateProfileResponse
{
    public bool Success { get; set; }
    public string Message { get; set; } = string.Empty;
}

public record UpdateProfileCommand(UpdateProfileRequest Data) : IRequest<UpdateProfileResponse>;

public class UpdateProfileHandler : IRequestHandler<UpdateProfileCommand, UpdateProfileResponse>
{
    private readonly AppDbContext _context;

    public UpdateProfileHandler(AppDbContext context) => _context = context;

    public async Task<UpdateProfileResponse> Handle(UpdateProfileCommand request, CancellationToken cancellationToken)
    {
        var user = await _context.Users
            .FirstOrDefaultAsync(x => x.Id == request.Data.Id, cancellationToken);

        if (user == null)
            return new UpdateProfileResponse { Success = false, Message = "User not found" };

        user.FullName = $"{request.Data.FirstName} {request.Data.LastName}";
        user.FirstName = request.Data.FirstName;
        user.LastName = request.Data.LastName;
        user.ShortBio = request.Data.ShortBio;
        user.JobTitle = request.Data.JobTitle;
        user.DateOfBirth = request.Data.DateOfBirth ?? user.DateOfBirth;
        user.PhoneNumber = request.Data.PhoneNumber;
        user.StreetAddress = request.Data.StreetAddress;
        user.City = request.Data.City;
        user.Country = request.Data.Country;
        user.ZipCode = request.Data.ZipCode;
        user.SocialMediaLinkedIn = request.Data.SocialMediaLinkedIn ?? string.Empty;
        user.SocialMediaInstagram = request.Data.SocialMediaInstagram ?? string.Empty;
        user.SocialMediaX = request.Data.SocialMediaX ?? string.Empty;
        user.UpdatedAt = DateTime.Now;

        await _context.SaveChangesAsync(cancellationToken);

        return new UpdateProfileResponse { Success = true };
    }
}