package com.prudas.app.service;

import com.prudas.app.dto.JobPostingRequest;
import com.prudas.app.dto.JobPostingResponse;
import com.prudas.app.entity.JobPosting;
import com.prudas.app.exception.ResourceNotFoundException;
import com.prudas.app.repository.JobPostingRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class JobPostingService {

    private final JobPostingRepository repository;

    public List<JobPostingResponse> findPublished() {
        return repository.findByPublishedTrueOrderByPostedAtDesc().stream().map(this::toResponse).toList();
    }

    public List<JobPostingResponse> findAllForAdmin() {
        return repository.findAll().stream().map(this::toResponse).toList();
    }

    @Transactional
    public JobPostingResponse create(JobPostingRequest request) {
        JobPosting entity = JobPosting.builder()
                .title(request.title()).department(request.department()).location(request.location())
                .employmentType(request.employmentType()).description(request.description())
                .applyEmail(request.applyEmail()).published(request.published())
                .build();
        return toResponse(repository.save(entity));
    }

    @Transactional
    public JobPostingResponse update(Long id, JobPostingRequest request) {
        JobPosting entity = repository.findById(id).orElseThrow(() -> new ResourceNotFoundException("Job posting not found: " + id));
        entity.setTitle(request.title());
        entity.setDepartment(request.department());
        entity.setLocation(request.location());
        entity.setEmploymentType(request.employmentType());
        entity.setDescription(request.description());
        entity.setApplyEmail(request.applyEmail());
        entity.setPublished(request.published());
        return toResponse(repository.save(entity));
    }

    @Transactional
    public void delete(Long id) {
        if (!repository.existsById(id)) {
            throw new ResourceNotFoundException("Job posting not found: " + id);
        }
        repository.deleteById(id);
    }

    private JobPostingResponse toResponse(JobPosting e) {
        return new JobPostingResponse(e.getId(), e.getTitle(), e.getDepartment(), e.getLocation(), e.getEmploymentType(), e.getDescription(), e.getApplyEmail(), e.isPublished(), e.getPostedAt());
    }
}
