import { Response } from "express";
import { AuthenticatedRequest } from "../types/auth";
import * as svc from "../services/projectMgmtService";
import { logger } from "../utils/logger";

export async function getList(req: AuthenticatedRequest, res: Response) {
  try {
    const filter = req.query as Record<string, string>;
    const data = await svc.listProgress(filter);
    return res.json({ success: true, data });
  } catch (e: any) {
    logger.error("진행관리 목록 실패", { error: e.message });
    return res.status(500).json({ success: false, message: e.message });
  }
}

export async function getProjectNoOptions(_req: AuthenticatedRequest, res: Response) {
  try {
    const data = await svc.listProjectNoOptions();
    return res.json({ success: true, data });
  } catch (e: any) {
    logger.error("프로젝트번호 옵션 조회 실패", { error: e.message });
    return res.status(500).json({ success: false, message: e.message });
  }
}

export async function getById(req: AuthenticatedRequest, res: Response) {
  try {
    const { id } = req.params;
    const data = await svc.getById(id);
    if (!data) return res.status(404).json({ success: false, message: "프로젝트를 찾을 수 없습니다." });
    return res.json({ success: true, data });
  } catch (e: any) {
    logger.error("진행관리 상세 실패", { error: e.message });
    return res.status(500).json({ success: false, message: e.message });
  }
}

export async function update(req: AuthenticatedRequest, res: Response) {
  try {
    const { id } = req.params;
    const rowCount = await svc.updateProject(id, req.body);
    if (rowCount === 0) return res.status(404).json({ success: false, message: "프로젝트를 찾을 수 없습니다." });
    return res.json({ success: true, message: "프로젝트가 수정되었습니다." });
  } catch (e: any) {
    logger.error("진행관리 수정 실패", { error: e.message });
    return res.status(500).json({ success: false, message: e.message });
  }
}
