package br.gov.sigefp.common.domain;

import jakarta.persistence.Embeddable;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.time.YearMonth;
import java.time.format.DateTimeFormatter;

/**
 * Value Object para representar um período (ano-mês).
 * Evita concatenar strings para datas e garante consistência.
 */
@Embeddable
@Getter
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
public class PeriodId {

    private Integer year;
    private Integer month;

    public static PeriodId of(int year, int month) {
        if (month < 1 || month > 12) {
            throw new IllegalArgumentException("Mês deve estar entre 1 e 12");
        }
        if (year < 2000 || year > 2100) {
            throw new IllegalArgumentException("Ano deve estar entre 2000 e 2100");
        }
        return new PeriodId(year, month);
    }

    public static PeriodId of(YearMonth yearMonth) {
        return new PeriodId(yearMonth.getYear(), yearMonth.getMonthValue());
    }

    public static PeriodId current() {
        return of(YearMonth.now());
    }

    public YearMonth toYearMonth() {
        return YearMonth.of(year, month);
    }

    public String toString() {
        return String.format("%04d-%02d", year, month);
    }

    public static PeriodId fromString(String period) {
        YearMonth ym = YearMonth.parse(period, DateTimeFormatter.ofPattern("yyyy-MM"));
        return of(ym);
    }
}

