using System.ComponentModel.DataAnnotations;
using ERPCore.Domain.Enums;

namespace ERPCore.Dtos.Sales;

// Responses -----------------------------------------------------------------

public sealed record SalesReturnLineDto(int ReturnLineId, int? SalesInvoiceLineId, int ItemId, decimal Qty);

public sealed record SalesReturnDto(
    int ReturnId, string DocNo, int CustomerId, int WarehouseId, int ReasonCodeId, ReturnStatus Status,
    int CreatedBy, DateTime CreatedAt, string? GlJournalNo, DateTime? GlPostedAt,
    IReadOnlyList<SalesReturnLineDto> Lines, IReadOnlyList<int> LedgerRefs);

/// <summary>Row shape for <c>GET /sales-returns</c> — no lines/ledgerRefs (those need a per-row query).</summary>
public sealed record SalesReturnSummaryDto(
    int ReturnId, string DocNo, int CustomerId, int WarehouseId, int ReasonCodeId, ReturnStatus Status,
    int CreatedBy, DateTime CreatedAt, int LineCount, decimal TotalQty, string? GlJournalNo);

/// <summary>
/// Remaining returnable qty for one sales invoice line — the invoiced qty minus
/// whatever has already been returned against it. The invoice line's own <c>Qty</c>
/// is never mutated by a return, so this is computed on read from return history.
/// </summary>
public sealed record SalesInvoiceLineRemainingDto(int SalesInvoiceLineId, decimal RemainingQty);

// Requests --------------------------------------------------------------------

public sealed class CreateSalesReturnLineInput
{
    /// <summary>Original sales invoice line, for traceability against the sale.</summary>
    public int? SalesInvoiceLineId { get; set; }
    [Required] public int ItemId { get; set; }
    [Range(0.0001, double.MaxValue)] public decimal Qty { get; set; }
}

public sealed class CreateSalesReturnRequest
{
    [Required] public int CustomerId { get; set; }
    [Required] public int WarehouseId { get; set; }
    /// <summary>Nullable so an omitted value is a distinct <c>REASON_CODE_REQUIRED</c> error.</summary>
    public int? ReasonCodeId { get; set; }
    [Required, MinLength(1)] public List<CreateSalesReturnLineInput> Lines { get; set; } = new();
}
