namespace Inspectron.Epson.Templates.Configuration;

public class TemplateResolver
{
    private readonly List<TemplateAssignment> _assignments;
    private readonly string _fallbackTemplate;

    public TemplateResolver(TemplateConfiguration configuration)
    {
        _assignments = configuration.GetAssignments().ToList();
        _fallbackTemplate = configuration.FallbackTemplate;
    }

    public TemplateResolver(IEnumerable<TemplateAssignment> assignments, string fallbackTemplate = "fallback.template")
    {
        _assignments = assignments.ToList();
        _fallbackTemplate = fallbackTemplate;
    }

    public string Resolve(int receiptType, string profileId)
    {
        // Priority 1: Exact match (receiptType + profileId)
        var exactMatch = _assignments.FirstOrDefault(a => a.MatchesExact(receiptType, profileId));
        if (exactMatch != null)
        {
            return exactMatch.TemplatePath;
        }

        // Priority 2: Type-only match (receiptType without profileId)
        var typeMatch = _assignments.FirstOrDefault(a => a.MatchesTypeOnly(receiptType));
        if (typeMatch != null)
        {
            return typeMatch.TemplatePath;
        }

        // Priority 3: Fallback
        return _fallbackTemplate;
    }

    public string Resolve(int receiptType, byte printerId, PrinterProfileRegistry registry)
    {
        var profile = registry.GetProfile(printerId);
        return Resolve(receiptType, profile.Id);
    }
}
