package com.zioinfo.kintex.system.program;

import com.zioinfo.kintex.common.error.ApiException;
import com.zioinfo.kintex.common.error.ErrorCode;
import com.zioinfo.kintex.tenant.TenantContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/** 프로그램(화면) 등록부 서비스. 테넌트 스코프. */
@Service
public class ProgramService {

    private final ProgramMapper mapper;

    public ProgramService(ProgramMapper mapper) {
        this.mapper = mapper;
    }

    public List<ProgramDto> list(String keyword, String category) {
        return mapper.findAll(TenantContext.currentTenantId(), keyword, category).stream()
                .map(ProgramService::toDto).toList();
    }

    @Transactional
    public void save(ProgramSaveRequest req) {
        String id = (req.id() == null || req.id().isBlank())
                ? "prg-" + UUID.randomUUID().toString().substring(0, 12) : req.id();
        Map<String, Object> p = new HashMap<>();
        p.put("tenantId", TenantContext.currentTenantId());
        p.put("id", id);
        p.put("programName", req.programName());
        p.put("programType", req.programType());
        p.put("programUrl", req.programUrl());
        p.put("category", req.category());
        p.put("useYn", req.useYn());
        mapper.upsert(p);
    }

    @Transactional
    public void delete(String id) {
        if (mapper.delete(TenantContext.currentTenantId(), id) == 0) {
            throw new ApiException(ErrorCode.NOT_FOUND);
        }
    }

    private static ProgramDto toDto(Map<String, Object> r) {
        return new ProgramDto(str(r.get("id")), str(r.get("programName")), str(r.get("programType")),
                str(r.get("programUrl")), str(r.get("category")), str(r.get("useYn")));
    }
    private static String str(Object o) { return o == null ? null : String.valueOf(o); }
}
