package kr.co.accura.wtm.domain.teal.service;

import kr.co.accura.wbx.spring.common.BusinessException;
import kr.co.accura.wbx.spring.common.NotFoundException;
import kr.co.accura.wtm.domain.project.entity.Project;
import kr.co.accura.wtm.domain.project.repository.ProjectRepository;
import kr.co.accura.wtm.domain.teal.dto.TealEntryDto;
import kr.co.accura.wtm.domain.teal.dto.TealVersionDto;
import kr.co.accura.wtm.domain.teal.entity.TealEntry;
import kr.co.accura.wtm.domain.teal.entity.TealVersion;
import kr.co.accura.wtm.domain.teal.repository.TealEntryRepository;
import kr.co.accura.wtm.domain.teal.repository.TealVersionRepository;
import kr.co.accura.wtm.domain.wbs.repository.CanonicalWbsRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.util.List;

@Service
@Transactional
@RequiredArgsConstructor
public class TealService {

    private final TealVersionRepository tealVersionRepository;
    private final TealEntryRepository tealEntryRepository;
    private final CanonicalWbsRepository canonicalWbsRepository;
    private final ProjectRepository projectRepository;

    /**
     * Upload TEAL file - Activity list linked to Canonical WBS.
     */
    public TealVersionDto uploadTeal(Long projectId, MultipartFile file,
                                     LocalDate effectiveDate, String description) {
        Project project = projectRepository.findById(projectId)
                .orElseThrow(() -> new NotFoundException("Project not found: " + projectId));

        // TODO: Parse TEAL file (WBS Code | Activity Code | Activity Name | Discipline)
        // For now, create an empty version as a stub

        int nextVersion = tealVersionRepository
                .findMaxVersionByProjectId(projectId)
                .map(v -> v + 1).orElse(1);

        TealVersion version = TealVersion.builder()
                .project(project)
                .versionNumber(nextVersion)
                .effectiveDate(effectiveDate)
                .description(description)
                .status("DRAFT")
                .build();
        tealVersionRepository.save(version);

        return TealVersionDto.from(version, 0);
    }

    /**
     * Get TEAL versions for a project.
     */
    @Transactional(readOnly = true)
    public List<TealVersionDto> getVersions(Long projectId) {
        return tealVersionRepository.findByProject_IdOrderByVersionNumberDesc(projectId).stream()
                .map(v -> {
                    int count = tealEntryRepository.findByTealVersion_Id(v.getId()).size();
                    return TealVersionDto.from(v, count);
                })
                .toList();
    }

    /**
     * Get active TEAL entries for timesheet input.
     */
    @Transactional(readOnly = true)
    public List<TealEntryDto> getActiveTealEntries(Long projectId) {
        TealVersion activeVersion = tealVersionRepository.findByProject_IdAndStatus(projectId, "ACTIVE")
                .orElseThrow(() -> new NotFoundException("No active TEAL version found for project: " + projectId));

        return tealEntryRepository.findByTealVersion_IdAndIsActiveTrue(activeVersion.getId()).stream()
                .map(TealEntryDto::from)
                .toList();
    }

    /**
     * Get TEAL entries by canonical WBS ID.
     */
    @Transactional(readOnly = true)
    public List<TealEntryDto> getEntriesByWbs(Long projectId, Long wbsId) {
        return tealEntryRepository.findByCanonicalWbs_Id(wbsId).stream()
                .map(TealEntryDto::from)
                .toList();
    }
}
