package com.zioinfo.hrm.uiws.system.service;

import com.zioinfo.hrm.uiws.common.UiwsApiException;
import com.zioinfo.hrm.uiws.common.UiwsErrorCode;
import com.zioinfo.hrm.uiws.system.dto.CompanyDto;
import com.zioinfo.hrm.uiws.system.dto.CompanySaveDto;
import com.zioinfo.hrm.uiws.system.dto.PageResponse;
import com.zioinfo.hrm.uiws.system.mapper.CompanyMapper;
import com.zioinfo.hrm.uiws.system.model.SysCompany;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/** 2.4 거래처(companies) CRUD + 검색팝업 + 다중삭제. */
@Service
@RequiredArgsConstructor
public class CompanyService {

    private final CompanyMapper companyMapper;

    @Transactional(readOnly = true)
    public PageResponse<CompanyDto> list(String keyword, int page, int size) {
        List<CompanyDto> content = companyMapper.search(keyword, page * size, size).stream().map(this::toDto).toList();
        return PageResponse.of(content, companyMapper.countSearch(keyword), page, size);
    }

    @Transactional(readOnly = true)
    public List<CompanyDto> searchPopup(String keyword) {
        return companyMapper.searchActive(keyword).stream().map(this::toDto).toList();
    }

    @Transactional(readOnly = true)
    public CompanyDto get(String companyId) {
        return toDto(find(companyId));
    }

    @Transactional
    public CompanyDto create(CompanySaveDto dto) {
        if (dto.companyId() == null || dto.companyId().isBlank()) {
            throw new UiwsApiException(UiwsErrorCode.INVALID_REQUEST, "companyId는 등록 시 필수입니다.");
        }
        if (companyMapper.existsById(dto.companyId())) {
            throw new UiwsApiException(UiwsErrorCode.DUPLICATE_KEY, "이미 존재하는 거래처 ID입니다.");
        }
        SysCompany c = new SysCompany();
        c.setCompanyId(dto.companyId());
        c.setCompanyNm(dto.companyNm());
        c.setBizNo(dto.bizNo());
        c.setUseYn(dto.useYn());
        c.setCreatedBy(SysActor.id());
        companyMapper.insert(c);
        return toDto(find(dto.companyId()));
    }

    @Transactional
    public CompanyDto update(String companyId, CompanySaveDto dto) {
        SysCompany c = find(companyId);
        c.setCompanyNm(dto.companyNm());
        c.setBizNo(dto.bizNo());
        c.setUseYn(dto.useYn());
        c.setUpdatedBy(SysActor.id());
        companyMapper.update(c);
        return toDto(find(companyId));
    }

    @Transactional
    public void delete(List<String> ids) {
        for (String id : ids) {
            if (!companyMapper.existsById(id)) {
                throw new UiwsApiException(UiwsErrorCode.COMPANY_NOT_FOUND);
            }
            companyMapper.deleteById(id);
        }
    }

    private CompanyDto toDto(SysCompany c) {
        return new CompanyDto(c.getCompanyId(), c.getCompanyNm(), c.getBizNo(), c.getUseYn());
    }

    private SysCompany find(String companyId) {
        SysCompany c = companyMapper.findById(companyId);
        if (c == null) {
            throw new UiwsApiException(UiwsErrorCode.COMPANY_NOT_FOUND);
        }
        return c;
    }
}
