import { Router } from 'express';
import { prisma } from '../lib/prisma';
import { AppError } from '../middleware/errorHandler';

const router = Router();

// GET /api/kpi?quarter=2026-Q2  — 분기별 KPI 전체 조회
router.get('/', async (req, res, next) => {
  try {
    const { quarter } = req.query as { quarter?: string };

    const metrics = await prisma.kpiMetric.findMany({
      where: quarter ? { quarter } : undefined,
      include: {
        task: { select: { id: true, title: true, status: true, assigneeId: true } },
      },
      orderBy: { createdAt: 'desc' },
    });

    res.json(metrics);
  } catch (err) {
    next(err);
  }
});

// POST /api/kpi  — KPI 등록
router.post('/', async (req, res, next) => {
  try {
    const { taskId, quarter, target, actual, unit } = req.body as {
      taskId: string;
      quarter: string;
      target: number;
      actual?: number;
      unit?: string;
    };

    if (!taskId || !quarter || target === undefined) {
      throw new AppError(400, 'taskId, quarter, target 은 필수입니다.');
    }

    const metric = await prisma.kpiMetric.create({
      data: { taskId, quarter, target: Number(target), actual: Number(actual ?? 0), unit },
    });

    res.status(201).json(metric);
  } catch (err) {
    next(err);
  }
});

// PATCH /api/kpi/:id  — KPI 수정 (실적 업데이트 등)
router.patch('/:id', async (req, res, next) => {
  try {
    const { target, actual, unit } = req.body as {
      target?: number;
      actual?: number;
      unit?: string;
    };

    const metric = await prisma.kpiMetric.update({
      where: { id: req.params.id },
      data: {
        ...(target !== undefined && { target: Number(target) }),
        ...(actual !== undefined && { actual: Number(actual) }),
        ...(unit !== undefined && { unit }),
      },
    });

    res.json(metric);
  } catch (err) {
    next(err);
  }
});

export default router;
