using Meezi.API.Models.Cafes;
using Meezi.API.Models.Public;
using Meezi.Infrastructure.Branding;
using Meezi.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;

namespace Meezi.API.Services;

public interface IBranchIdentityService
{
    Task<BranchEffectiveIdentityDto?> GetEffectiveIdentityAsync(
        string cafeId,
        string branchId,
        CancellationToken cancellationToken = default);
}

public record BranchEffectiveIdentityDto(
    string PrimaryColor,
    string SecondaryColor,
    string? FontFamily,
    string? LogoUrl,
    string? IconName,
    string WelcomeText,
    string? WifiPassword,
    string? Address,
    string? AccentColor);

public class BranchIdentityService : IBranchIdentityService
{
    private const string DefaultPrimary = "#0F6E56";
    private const string DefaultSecondary = "#E1F5EE";

    private readonly AppDbContext _db;

    public BranchIdentityService(AppDbContext db)
    {
        _db = db;
    }

    public async Task<BranchEffectiveIdentityDto?> GetEffectiveIdentityAsync(
        string cafeId,
        string branchId,
        CancellationToken cancellationToken = default)
    {
        var branch = await _db.Branches
            .Include(b => b.Cafe)
            .FirstOrDefaultAsync(
                b => b.Id == branchId && b.CafeId == cafeId && b.IsActive,
                cancellationToken);

        if (branch?.Cafe is null) return null;

        var theme = CafeThemeSerializer.Parse(branch.Cafe.ThemeJson);
        var primary = theme.Custom?.Primary?.Trim();
        if (string.IsNullOrEmpty(primary))
            primary = DefaultPrimary;

        var secondary = theme.Custom?.Secondary?.Trim();
        if (string.IsNullOrEmpty(secondary))
            secondary = DefaultSecondary;

        var logo = !string.IsNullOrWhiteSpace(branch.LogoUrl)
            ? branch.LogoUrl
            : branch.Cafe.LogoUrl;

        var welcome = !string.IsNullOrWhiteSpace(branch.WelcomeText)
            ? branch.WelcomeText.Trim()
            : "خوش آمدید";

        return new BranchEffectiveIdentityDto(
            primary,
            secondary,
            null,
            logo,
            "coffee",
            welcome,
            branch.WifiPassword,
            branch.Address ?? branch.Cafe.Address,
            branch.AccentColor);
    }
}
