package com.ga.api.service.license;

import com.ga.common.exception.BizException;
import com.ga.common.exception.ErrorCode;
import com.ga.common.model.PageResponse;
import com.ga.core.mapper.license.AgentLicenseMapper;
import com.ga.core.vo.license.*;
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 AgentLicenseService {

    private final AgentLicenseMapper mapper;

    public PageResponse<AgentLicenseResp> list(AgentLicenseSearchParam param) {
        param.startPage();
        return PageResponse.of(mapper.selectList(param));
    }

    public AgentLicenseResp detail(Long licenseId) {
        AgentLicenseResp resp = mapper.selectById(licenseId);
        if (resp == null) throw new BizException(ErrorCode.NOT_FOUND);
        return resp;
    }

    public List<AgentLicenseResp> expiring(int days) {
        return mapper.selectExpiringWithin(days);
    }

    @Transactional
    public Long create(AgentLicenseSaveReq req) {
        AgentLicenseVO vo = new AgentLicenseVO();
        vo.setAgentId(req.getAgentId());
        vo.setLicenseType(req.getLicenseType());
        vo.setLicenseNo(req.getLicenseNo());
        vo.setIssuedDate(req.getIssuedDate());
        vo.setExpiresDate(req.getExpiresDate());
        vo.setRenewedFrom(req.getRenewedFrom());
        vo.setStatus(LicenseStatus.ACTIVE.name());
        mapper.insert(vo);
        return vo.getLicenseId();
    }

    @Transactional
    public void update(Long licenseId, AgentLicenseSaveReq req) {
        AgentLicenseResp existing = mapper.selectById(licenseId);
        if (existing == null) throw new BizException(ErrorCode.NOT_FOUND);
        AgentLicenseVO vo = new AgentLicenseVO();
        vo.setLicenseId(licenseId);
        vo.setAgentId(req.getAgentId());
        vo.setLicenseType(req.getLicenseType());
        vo.setLicenseNo(req.getLicenseNo());
        vo.setIssuedDate(req.getIssuedDate());
        vo.setExpiresDate(req.getExpiresDate());
        vo.setRenewedFrom(req.getRenewedFrom());
        mapper.update(vo);
    }

    @Transactional
    public void delete(Long licenseId) {
        AgentLicenseResp existing = mapper.selectById(licenseId);
        if (existing == null) throw new BizException(ErrorCode.NOT_FOUND);
        mapper.delete(licenseId);
    }
}
