package kr.co.accura.wtm.domain.wbs.entity;

import jakarta.persistence.*;
import lombok.*;

import java.time.LocalDateTime;

@Entity
@Table(name = "canonical_wbs",
        uniqueConstraints = @UniqueConstraint(columnNames = {"project_id", "wbs_code"}))
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class CanonicalWbs {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "project_id", nullable = false)
    private Long projectId;

    @Column(name = "wbs_code", nullable = false, length = 100)
    private String wbsCode;

    @Column(nullable = false)
    private Integer level;

    @Column(nullable = false, length = 500)
    private String name;

    @Column(name = "parent_code", length = 100)
    private String parentCode;

    @Column(length = 50)
    private String discipline;

    @Column(name = "is_active")
    @Builder.Default
    private Boolean isActive = true;

    @Column(name = "mapped_p6_code", length = 100)
    private String mappedP6Code;

    @Column(name = "created_at")
    @Builder.Default
    private LocalDateTime createdAt = LocalDateTime.now();

    public static CanonicalWbs fromWbsNode(Long projectId, WbsNode node) {
        return CanonicalWbs.builder()
                .projectId(projectId)
                .wbsCode(node.getWbsCode())
                .level(node.getLevel())
                .name(node.getName())
                .parentCode(node.getParent() != null ? node.getParent().getWbsCode() : null)
                .discipline(node.getDiscipline())
                .mappedP6Code(node.getWbsCode())
                .build();
    }

    public void updateFrom(WbsNode node) {
        this.name = node.getName();
        this.level = node.getLevel();
        this.discipline = node.getDiscipline();
    }
}
