package com.devjob.service;

import com.devjob.domain.Company;
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.CompanyRepository;
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;

/**
 * EP13: Job ↔ Company 연관관계 적용.
 * 등록 시 companyId로 Company를 조회해 연관관계를 맺고,
 * 목록 조회는 fetch join 쿼리(findByStatusWithCompany)로 N+1을 방지한다.
 */
@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class JobService {

    private final JobRepository jobRepository;
    private final CompanyRepository companyRepository;

    @Transactional
    public JobResponse create(JobCreateRequest req) {
        Company company = companyRepository.findById(req.companyId())
                .orElseThrow(() -> new BusinessException(ErrorCode.COMPANY_NOT_FOUND));

        Job job = new Job();
        job.setCompany(company);
        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.findByStatusWithCompany(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);
    }
}
