using System.Text.Json;

namespace Books.Api.EventFlow.ReadModels;

/// <summary>
/// DTO for Invoice read model, used for Dapper queries.
/// </summary>
public class InvoiceReadModelDto
{
    public string Id { get; set; } = string.Empty;
    public string CompanyId { get; set; } = string.Empty;
    public string? FiscalYearId { get; set; }
    public string CustomerId { get; set; } = string.Empty;
    public string CustomerName { get; set; } = string.Empty;
    public string CustomerNumber { get; set; } = string.Empty;
    public string InvoiceNumber { get; set; } = string.Empty;
    public DateTime? InvoiceDate { get; set; }
    public DateTime? DueDate { get; set; }

    // Document type (invoice or credit_note)
    public string InvoiceType { get; set; } = "invoice";

    // Credit note specific fields
    public string? OriginalInvoiceId { get; set; }
    public string? OriginalInvoiceNumber { get; set; }
    public string? CreditReason { get; set; }

    public string Status { get; set; } = "draft";
    public decimal AmountExVat { get; set; }
    public decimal AmountVat { get; set; }
    public decimal AmountTotal { get; set; }
    public decimal AmountPaid { get; set; }
    public decimal AmountApplied { get; set; } // For credit notes
    public decimal AmountRemaining { get; set; }
    public string Currency { get; set; } = "DKK";
    public string? VatCode { get; set; }
    public int PaymentTermsDays { get; set; }
    public string LinesJson { get; set; } = "[]";
    public string? LedgerTransactionId { get; set; }
    public string? Notes { get; set; }
    public string? Reference { get; set; }
    public DateTime? SentAt { get; set; }
    public DateTime? IssuedAt { get; set; } // For credit notes
    public DateTime? PaidAt { get; set; }
    public DateTime? VoidedAt { get; set; }
    public string? VoidedReason { get; set; }
    public string? VoidedBy { get; set; }
    public string CreatedBy { get; set; } = string.Empty;
    public string? UpdatedBy { get; set; }
    public DateTime CreatedAt { get; set; }
    public DateTime UpdatedAt { get; set; }

    /// <summary>
    /// Returns true if this is a credit note.
    /// </summary>
    public bool IsCreditNote => InvoiceType == "credit_note";

    /// <summary>
    /// Parses the Lines JSON into a list of InvoiceLineDto.
    /// </summary>
    public IReadOnlyList<InvoiceLineDto> GetLines()
    {
        if (string.IsNullOrEmpty(LinesJson))
            return [];

        try
        {
            return JsonSerializer.Deserialize<List<InvoiceLineDto>>(LinesJson) ?? [];
        }
        catch
        {
            return [];
        }
    }
}
