package com.devjob.application.domain;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import jakarta.persistence.UniqueConstraint;
import java.time.LocalDateTime;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

/**
 * 지원 내역. application_db가 단독 소유한다.
 *
 * EP08: 시즌1에서는 Member/Job을 @ManyToOne으로 직접 참조했지만,
 * MSA에서는 다른 서비스의 엔티티를 참조할 수 없으므로 userId/jobId(Long)만 보관한다 (EP02 원칙).
 * (member_id, job_id) → (user_id, job_id) 유니크 제약으로 중복 지원을 방지한다.
 */
@Entity
@Table(name = "application", uniqueConstraints = {
        @UniqueConstraint(name = "uk_application_user_job", columnNames = {"user_id", "job_id"})
})
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@EntityListeners(AuditingEntityListener.class)
public class Application {

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

    @Column(name = "user_id", nullable = false)
    private Long userId;

    @Column(name = "job_id", nullable = false)
    private Long jobId;

    @Enumerated(EnumType.STRING)
    @Column(nullable = false, length = 20)
    private ApplicationStatus status;

    @CreatedDate
    @Column(updatable = false)
    private LocalDateTime createdAt;

    @Builder
    public Application(Long userId, Long jobId) {
        this.userId = userId;
        this.jobId = jobId;
        this.status = ApplicationStatus.APPLIED;
    }

    public void cancel() {
        this.status = ApplicationStatus.CANCELLED;
    }

    public void changeStatus(ApplicationStatus status) {
        this.status = status;
    }
}
