namespace TaxBaik.Application.Services;

using System.Text.RegularExpressions;
using FluentValidation;
using Microsoft.Extensions.Caching.Memory;
using TaxBaik.Application.DTOs;
using TaxBaik.Domain.Entities;
using TaxBaik.Domain.Enums;
using TaxBaik.Domain.Interfaces;

public class InquiryService(
    IInquiryRepository repository,
    IInquiryNotificationService notificationService,
    IMemoryCache memoryCache,
    IValidator<SubmitInquiryDto> submitValidator,
    IValidator<UpdateInquiryDto> updateValidator)
{
    // 한국 전화번호 정규식
    // 휴대폰: 010~019, 070, 0505~0509
    // 고정전화: 02, 031~064
    private static readonly Regex PhoneRegex = new(
        @"^(0(?:2|3[1-3]|4[1-4]|5[1-5]|6[1-4]|70|50[5-9]|[7-9](?:\d{1,2})?)\d{7,8}|0\d{9,10})$");

    public async Task<int> SubmitAsync(
        string name, string phone, string serviceType, string message,
        string? email = null, string? ipAddress = null, bool suppressNotification = false, CancellationToken ct = default)
    {
        submitValidator.ValidateAndThrow(new SubmitInquiryDto
        {
            Name = name,
            Phone = phone,
            Email = email,
            ServiceType = serviceType,
            Message = message
        });

        var cleanPhone = phone?.Replace("-", "").Replace(" ", "").Trim() ?? "";
        if (!PhoneRegex.IsMatch(cleanPhone) || cleanPhone.Length < 10)
            throw new ValidationException("올바른 전화번호를 입력하세요. (예: 01012345678 또는 010-1234-5678)");

        var formattedPhone = FormatPhoneNumber(cleanPhone);

        var trimmedMessage = message.Trim();

        var inquiry = new Inquiry
        {
            Name = name.Trim(),
            Phone = formattedPhone,
            Email = string.IsNullOrWhiteSpace(email) ? null : email.Trim(),
            ServiceType = serviceType ?? "기타",
            Message = trimmedMessage,
            IpAddress = ipAddress,
            Status = InquiryStatusMapper.ToStorageValue(InquiryStatus.New),
            CreatedAt = DateTime.UtcNow
        };

        var inquiryId = await repository.CreateAsync(inquiry, ct);
        if (!suppressNotification)
        {
            await notificationService.NotifyCreatedAsync(inquiryId, inquiry.Name, inquiry.Phone, inquiry.ServiceType, inquiry.Message, inquiry.IpAddress, inquiry.CreatedAt, ct);
        }
        memoryCache.Remove(AdminDashboardService.CacheKey);
        return inquiryId;
    }

    public async Task<Inquiry?> GetByIdAsync(int id, CancellationToken ct = default) =>
        await repository.GetByIdAsync(id, ct);

    public async Task<(IEnumerable<Inquiry>, int)> GetPagedAsync(
        int page, int pageSize, string? status = null, CancellationToken ct = default) =>
        await repository.GetPagedAsync(NormalizePage(page), NormalizePageSize(pageSize), NormalizeOptionalStatus(status), ct);

    public Task<int> CountAsync(CancellationToken ct = default)
        => repository.CountAsync(ct);

    public Task<int> CountThisMonthAsync(CancellationToken ct = default)
        => repository.CountThisMonthAsync(ct);

    public Task<int> CountByStatusAsync(string status, CancellationToken ct = default)
        => repository.CountByStatusAsync(status, ct);

    public Task<int> CountByDateRangeAsync(DateTime startDate, DateTime endDate, CancellationToken ct = default)
        => repository.CountByDateRangeAsync(startDate, endDate, ct);

    public Task<int> CountByStatusAndDateAsync(string status, DateTime startDate, DateTime endDate, CancellationToken ct = default)
        => repository.CountByStatusAndDateAsync(status, startDate, endDate, ct);

    public async Task UpdateAdminMemoAsync(int id, string? adminMemo, CancellationToken ct = default) =>
        await repository.UpdateAdminMemoAsync(id, adminMemo, ct);

    public async Task<Inquiry?> UpdateAsync(int id, UpdateInquiryDto dto, CancellationToken ct = default)
    {
        var inquiry = await repository.GetByIdAsync(id, ct);
        if (inquiry == null)
            return null;
        updateValidator.ValidateAndThrow(dto);

        var cleanPhone = dto.Phone?.Replace("-", "").Replace(" ", "").Trim() ?? "";
        if (!PhoneRegex.IsMatch(cleanPhone) || cleanPhone.Length < 10)
            throw new ValidationException("올바른 전화번호를 입력하세요. (예: 01012345678 또는 010-1234-5678)");

        var trimmedUpdateMessage = dto.Message.Trim();

        if (!InquiryStatusMapper.TryParse(dto.Status, out var parsedStatus))
            throw new ValidationException("지원하지 않는 문의 상태입니다.");

        inquiry.Name = dto.Name.Trim();
        inquiry.Phone = FormatPhoneNumber(cleanPhone);
        inquiry.Email = string.IsNullOrWhiteSpace(dto.Email) ? null : dto.Email.Trim();
        inquiry.ServiceType = string.IsNullOrWhiteSpace(dto.ServiceType) ? "기타" : dto.ServiceType.Trim();
        inquiry.Message = trimmedUpdateMessage;
        inquiry.Status = InquiryStatusMapper.ToStorageValue(parsedStatus);
        inquiry.AdminMemo = dto.AdminMemo;

        await repository.UpdateAsync(inquiry, ct);
        memoryCache.Remove(AdminDashboardService.CacheKey);
        return inquiry;
    }

    public async Task LinkClientAsync(int inquiryId, int clientId, CancellationToken ct = default) =>
        await repository.LinkClientAsync(inquiryId, clientId, ct);

    public async Task UpdateStatusAsync(int id, string status, string? changedBy = null, CancellationToken ct = default)
    {
        if (!InquiryStatusMapper.TryParse(status, out var parsed))
            throw new ValidationException("지원하지 않는 문의 상태입니다.");

        var inquiry = await repository.GetByIdAsync(id, ct);
        if (inquiry == null)
            return;

        var previousStatus = inquiry.Status;
        var newStatus = InquiryStatusMapper.ToStorageValue(parsed);

        await repository.UpdateStatusAsync(id, newStatus, ct);
        await notificationService.NotifyStatusChangedAsync(id, inquiry.Name, inquiry.Phone, inquiry.ServiceType, previousStatus, newStatus, changedBy, ct);
        memoryCache.Remove(AdminDashboardService.CacheKey);
    }

    public async Task DeleteAsync(int id, CancellationToken ct = default)
    {
        await repository.DeleteAsync(id, ct);
        memoryCache.Remove(AdminDashboardService.CacheKey);
    }

    private static int NormalizePage(int page) => Math.Max(1, page);

    private static int NormalizePageSize(int pageSize) => Math.Clamp(pageSize, 1, 100);

    private static string? NormalizeOptionalStatus(string? status)
    {
        if (string.IsNullOrWhiteSpace(status))
            return null;

        if (!InquiryStatusMapper.TryParse(status, out var parsed))
            throw new ValidationException("지원하지 않는 문의 상태입니다.");

        return InquiryStatusMapper.ToStorageValue(parsed);
    }

    private static string FormatPhoneNumber(string phone)
    {
        if (string.IsNullOrWhiteSpace(phone))
            return phone ?? "";

        var clean = phone.Replace("-", "").Replace(" ", "").Trim();
        if (clean.Length < 10 || clean.Length > 11 || !clean.StartsWith("0"))
            return clean;

        // 국번 추출 (2-3자리)
        var areaCode = GetAreaCode(clean);
        if (string.IsNullOrEmpty(areaCode))
            return clean;

        var restLength = clean.Length - areaCode.Length;
        var restPart = clean.Substring(areaCode.Length);

        // 나머지 부분을 3-4 또는 4-4로 분할
        if (restLength == 7)
            return $"{areaCode}-{restPart[..3]}-{restPart[3..]}";  // XXX-XXX-XXXX
        else if (restLength == 8)
            return $"{areaCode}-{restPart[..4]}-{restPart[4..]}";  // XXX-XXXX-XXXX
        else
            return clean;
    }

    private static string GetAreaCode(string phone)
    {
        if (phone.Length < 10 || !phone.StartsWith("0"))
            return "";

        // 3자리 국번: 070, 0505~0509
        if ((phone.StartsWith("070") ||
             (phone.StartsWith("050") && phone.Length > 2 && phone[3] >= '5' && phone[3] <= '9')))
            return phone[..3];

        // 3자리 국번: 031~064
        if (phone.Length >= 3 &&
            phone[0] == '0' &&
            char.IsDigit(phone[1]) && char.IsDigit(phone[2]))
        {
            var areaPrefix = int.Parse(phone.Substring(1, 2));
            if ((areaPrefix >= 31 && areaPrefix <= 39) ||  // 경기, 인천
                (areaPrefix >= 41 && areaPrefix <= 48) ||  // 충청
                (areaPrefix >= 51 && areaPrefix <= 54) ||  // 부산, 울산
                (areaPrefix >= 61 && areaPrefix <= 64) ||  // 전라
                (areaPrefix >= 71 && areaPrefix <= 74))    // 경상
                return phone[..3];
        }

        // 2자리 국번: 02
        if (phone.StartsWith("02"))
            return "02";

        // 기타 휴대폰 (010~019)
        if (phone[0] == '0' && phone[1] == '1' && phone.Length >= 11)
            return phone[..3];

        return "";
    }
}

public class ValidationException : Exception
{
    public ValidationException(string message) : base(message) { }
}
