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

export async function getSaleList(req: AuthenticatedRequest, res: Response) {
  try {
    const data = await svc.getSaleList(req.query as any);
    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 getRevenueList(req: AuthenticatedRequest, res: Response) {
  try {
    const data = await svc.getRevenueList(req.query as any);
    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 registerSale(req: AuthenticatedRequest, res: Response) {
  try {
    const userId = req.user!.userId;
    const data = await svc.registerSale(userId, req.body);
    return res.status(201).json({ success: true, data, message: "판매가 등록되었습니다." });
  } catch (e: any) { return res.status(500).json({ success: false, message: e.message }); }
}

export async function deleteSale(req: AuthenticatedRequest, res: Response) {
  try {
    await svc.deleteSale(req.params.projectNo);
    return res.json({ success: true, message: "판매가 삭제되었습니다." });
  } catch (e: any) { return res.status(500).json({ success: false, message: e.message }); }
}

export async function saveDeadlineInfo(req: AuthenticatedRequest, res: Response) {
  try {
    const userId = req.user!.userId;
    const data = await svc.saveDeadlineInfo(userId, req.body);
    return res.json({ success: true, data, message: "마감정보가 저장되었습니다." });
  } catch (e: any) { return res.status(500).json({ success: false, message: e.message }); }
}

export async function confirmSalesDeadline(req: AuthenticatedRequest, res: Response) {
  try {
    const userId = req.user!.userId;
    const { logIds } = req.body as { logIds: number[] };
    await svc.confirmSalesDeadline(userId, logIds);
    return res.json({ success: true, message: "매출 마감이 확정되었습니다." });
  } catch (e: any) { return res.status(500).json({ success: false, message: e.message }); }
}
