package com.devjob.domain;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
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;

/**
 * EP24: 지원 내역.
 * - (member_id, job_id) 조합은 유일해야 한다 — 같은 공고에 중복 지원 방지(UniqueConstraint).
 * - 애플리케이션 레벨에서도 ApplicationService.apply()에서 ALREADY_APPLIED를 먼저 검사한다.
 */
@Entity
@Table(name = "application", uniqueConstraints = {
        @UniqueConstraint(name = "uk_application_member_job", columnNames = {"member_id", "job_id"})
})
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@EntityListeners(AuditingEntityListener.class)
public class Application {

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

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "member_id", nullable = false)
    private Member member;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "job_id", nullable = false)
    private Job job;

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

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

    @Builder
    public Application(Member member, Job job) {
        this.member = member;
        this.job = job;
        this.status = ApplicationStatus.APPLIED;
    }

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

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