package com.sino.mci.channel.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sino.mci.channel.dto.CreateChannelSubjectRequest;
import com.sino.mci.channel.dto.UpdateStatusRequest;
import com.sino.mci.channel.entity.ChannelSubject;
import com.sino.mci.channel.entity.SyncTask;
import com.sino.mci.channel.repository.ChannelSubjectMapper;
import com.sino.mci.exception.BusinessException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class ChannelSubjectService {

    private final ChannelSubjectMapper subjectMapper;
    private final SyncTaskService syncTaskService;
    private final SyncTaskExecutor syncTaskExecutor;

    public List<ChannelSubject> listSubjects(String tenantCode) {
        return subjectMapper.selectList(
                new LambdaQueryWrapper<ChannelSubject>()
                        .eq(ChannelSubject::getTenantCode, tenantCode)
                        .eq(ChannelSubject::getStatus, 1)
                        .orderByDesc(ChannelSubject::getId));
    }

    public ChannelSubject getSubject(Long id, String tenantCode) {
        ChannelSubject subject = subjectMapper.selectById(id);
        if (subject == null || !tenantCode.equals(subject.getTenantCode())) {
            throw new BusinessException("渠道主体不存在: " + id);
        }
        return subject;
    }

    @Transactional
    public ChannelSubject createSubject(String tenantCode, CreateChannelSubjectRequest request) {
        ChannelSubject existing = subjectMapper.selectOne(
                new LambdaQueryWrapper<ChannelSubject>()
                        .eq(ChannelSubject::getTenantCode, tenantCode)
                        .eq(ChannelSubject::getChannelType, request.getChannelType())
                        .eq(ChannelSubject::getSubjectCode, request.getSubjectCode()));
        if (existing != null) {
            throw new BusinessException("渠道主体已存在: " + request.getSubjectCode());
        }

        ChannelSubject subject = new ChannelSubject();
        subject.setTenantCode(tenantCode);
        subject.setChannelType(request.getChannelType());
        subject.setSubjectCode(request.getSubjectCode());
        subject.setSubjectName(request.getSubjectName());
        subject.setCorpId(request.getCorpId());
        subject.setAgentId(request.getAgentId());
        subject.setAgentSecret(request.getAgentSecret());
        subject.setSessionArchiveEnabled(request.getSessionArchiveEnabled() != null ? request.getSessionArchiveEnabled() : 0);
        subject.setSessionArchivePrivateKey(request.getSessionArchivePrivateKey());
        subject.setStatus(1);
        subjectMapper.insert(subject);
        return subject;
    }

    @Transactional
    public ChannelSubject updateSubject(Long id, String tenantCode, CreateChannelSubjectRequest request) {
        ChannelSubject subject = getSubject(id, tenantCode);

        if (!subject.getSubjectCode().equals(request.getSubjectCode())) {
            ChannelSubject existing = subjectMapper.selectOne(
                    new LambdaQueryWrapper<ChannelSubject>()
                            .eq(ChannelSubject::getTenantCode, tenantCode)
                            .eq(ChannelSubject::getChannelType, request.getChannelType())
                            .eq(ChannelSubject::getSubjectCode, request.getSubjectCode()));
            if (existing != null) {
                throw new BusinessException("渠道主体编码已存在: " + request.getSubjectCode());
            }
        }

        subject.setChannelType(request.getChannelType());
        subject.setSubjectCode(request.getSubjectCode());
        subject.setSubjectName(request.getSubjectName());
        subject.setCorpId(request.getCorpId());
        subject.setAgentId(request.getAgentId());
        subject.setAgentSecret(request.getAgentSecret());
        subject.setSessionArchiveEnabled(request.getSessionArchiveEnabled() != null ? request.getSessionArchiveEnabled() : 0);
        subject.setSessionArchivePrivateKey(request.getSessionArchivePrivateKey());
        subjectMapper.updateById(subject);
        return subject;
    }

    @Transactional
    public void deleteSubject(Long id, String tenantCode) {
        ChannelSubject subject = getSubject(id, tenantCode);
        subject.setStatus(0);
        subjectMapper.updateById(subject);
    }

    @Transactional
    public ChannelSubject updateSubjectStatus(Long id, String tenantCode, UpdateStatusRequest request) {
        ChannelSubject subject = getSubject(id, tenantCode);
        subject.setStatus(request.getStatus());
        subjectMapper.updateById(subject);
        return subject;
    }

    public SyncTask submitEnterpriseContactsSyncTask(Long id, String tenantCode) {
        ChannelSubject subject = getSubject(id, tenantCode);
        SyncTask task = syncTaskService.createTask(
                tenantCode, "enterprise_contacts", subject.getChannelType(), id, subject.getSubjectCode());
        syncTaskExecutor.executeEnterpriseContactsSync(task.getId());
        return task;
    }
}
