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.dto.PageResponse;
import com.devjob.exception.BusinessException;
import com.devjob.exception.ErrorCode;
import com.devjob.repository.JobRepository;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * EP11: 메모리 Map 대신 JobRepository(JPA)를 사용하도록 전환.
 * Pageable + PageRequest 기반으로 목록을 조회한다.
 */
@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 PageResponse<JobResponse> findByStatus(JobStatus status, Pageable pageable) {
        return PageResponse.of(jobRepository.findByStatus(status, pageable).map(JobResponse::from));
    }

    @Transactional
    public void delete(Long id) {
        if (!jobRepository.existsById(id)) {
            throw new BusinessException(ErrorCode.JOB_NOT_FOUND);
        }
        jobRepository.deleteById(id);
    }
}
