package com.utic.center.utic.traf.server.service;

import com.utic.center.common.annotation.ProcessingElapsed;
import com.utic.center.common.service.AbstractProcessService;
import com.utic.center.utic.traf.server.dao.repository.dwdb.DwdbTableManagerRepository;
import com.utic.center.utic.traf.server.repository.ApplicationRepository;
import com.utic.center.utic.traf.server.service.partition.MakeTablePartition;
import com.utic.center.utic.traf.server.service.partition.TrafficCenterHist;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.YearMonth;
import java.time.format.DateTimeFormatter;

@Slf4j
@Getter
@RequiredArgsConstructor
@Service
public class DwdbTableManagerService implements AbstractProcessService {

    private final DwdbTableManagerRepository repo;

    @ProcessingElapsed(type="TABLE", name="Table Partition Manager", starting = false)
    @Override
    public boolean processing() {
        YearMonth next = YearMonth.now().plusMonths(1);
        final String nextMonth = next.format(DateTimeFormatter.ofPattern("yyMM"));       // 예: 2510
        final String commentNextMonth = next.format(DateTimeFormatter.ofPattern("yyyy년 MM월"));

        return createPartitionTable(nextMonth, commentNextMonth);
    }

    public boolean createCurrentPartitionTable() {
        YearMonth current = YearMonth.now();
        final String currMonth = current.format(DateTimeFormatter.ofPattern("yyMM"));    // 예: 2509
        final String commentCurrMonth = current.format(DateTimeFormatter.ofPattern("yyyy년 MM월"));

        return createPartitionTable(currMonth, commentCurrMonth);
    }

    private boolean createPartitionTable(String crtMonth, String commentCrtMonth) {
        // TRAFFIC_CENTER_HIST
        MakeTablePartition trafficCenter = new TrafficCenterHist(this.repo, crtMonth, commentCrtMonth);
        if (!trafficCenter.createPartitionTable()) {
            ApplicationRepository.processState.setError("create TrafficCenterHist table failed.");
            return false;
        }
        return true;
    }
}
