package com.devjob.service;

import com.devjob.domain.Job;
import com.devjob.domain.JobStatus;
import com.devjob.dto.JobCreateRequest;
import com.devjob.dto.JobResponse;
import com.devjob.repository.JobRepository;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * EP10: JobRepository(JpaRepository)를 사용하는 서비스 계층.
 * EP09까지 쓰던 인메모리 저장소(Map)를 걷어내고, 저장·조회·삭제를 모두
 * JobRepository에 위임한다. 컨트롤러(JobController)는 그대로 두어도
 * 이제 호출 결과가 PostgreSQL에 영속된다.
 * 클래스 레벨 @Transactional(readOnly = true)로 조회를 최적화하고,
 * 쓰기 메서드에는 별도로 @Transactional을 붙인다.
 */
@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class JobService {

    private final JobRepository jobRepository;

    @Transactional
    public JobResponse create(JobCreateRequest req) {
        Job job = new Job();
        job.setCompanyId(req.companyId());
        job.setTitle(req.title());
        job.setDescription(req.description());
        job.setSalary(req.salary());
        job.setStatus(JobStatus.OPEN);
        return JobResponse.from(jobRepository.save(job));
    }

    public Optional<JobResponse> findById(Long id) {
        return jobRepository.findById(id)
                .map(JobResponse::from);
    }

    public Page<JobResponse> findByStatus(String status, int page, int size) {
        JobStatus jobStatus = JobStatus.valueOf(status.toUpperCase());
        return jobRepository.findByStatus(jobStatus, PageRequest.of(page, size))
                .map(JobResponse::from);
    }

    @Transactional
    public void delete(Long id) {
        jobRepository.deleteById(id);
    }
}
