-- 008_create_update_triggers.sql
-- 작업보고서 변경 시 월별 집계 자동 업데이트 트리거

DELIMITER $$

-- 작업보고서 INSERT 트리거
CREATE OR REPLACE TRIGGER tr_daily_work_reports_insert
AFTER INSERT ON daily_work_reports
FOR EACH ROW
BEGIN
    CALL UpdateMonthlyWorkerStatus(NEW.report_date, NEW.worker_id);
END$$

-- 작업보고서 UPDATE 트리거
CREATE OR REPLACE TRIGGER tr_daily_work_reports_update
AFTER UPDATE ON daily_work_reports
FOR EACH ROW
BEGIN
    -- 기존 날짜 업데이트
    CALL UpdateMonthlyWorkerStatus(OLD.report_date, OLD.worker_id);
    
    -- 새 날짜가 다르면 새 날짜도 업데이트
    IF OLD.report_date != NEW.report_date OR OLD.worker_id != NEW.worker_id THEN
        CALL UpdateMonthlyWorkerStatus(NEW.report_date, NEW.worker_id);
    END IF;
END$$

-- 작업보고서 DELETE 트리거
CREATE OR REPLACE TRIGGER tr_daily_work_reports_delete
AFTER DELETE ON daily_work_reports
FOR EACH ROW
BEGIN
    CALL UpdateMonthlyWorkerStatus(OLD.report_date, OLD.worker_id);
END$$

DELIMITER ;
