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

const router = Router();
const HUB_ID = 'default';

export const DEFAULT_HUB_CONFIG = {
  sloganTitle: '분기 중점 과제',
  sloganLines: ['인사 · 육성 · 문화 · 총무', '개선과제', '정상 추진'],
  scheduleTitle: '분기 주요 일정',
  scheduleItems: [
    { id: '1', date: '2026-04-01', text: '상반기 채용·온보딩' },
    { id: '2', date: '2026-05-15', text: '조직문화 진단·리더십 교육' },
    { id: '3', date: '2026-06-20', text: '분기 성과 점검·평가' },
  ],
  routineLabels: ['채용 운영', '학습 지원', '직원 소통', '자산·시설', '문서·행정'],
};

function normalizeConfig(raw: Record<string, unknown>) {
  const sloganTitle = (raw.sloganTitle as string) ?? DEFAULT_HUB_CONFIG.sloganTitle;
  return {
    sloganTitle: sloganTitle === '분기 슬로건' ? '분기 중점 과제' : sloganTitle,
    sloganLines: Array.isArray(raw.sloganLines)
      ? (raw.sloganLines as string[])
      : DEFAULT_HUB_CONFIG.sloganLines,
    scheduleTitle: (raw.scheduleTitle as string) ?? DEFAULT_HUB_CONFIG.scheduleTitle,
    scheduleItems: Array.isArray(raw.scheduleItems)
      ? (raw.scheduleItems as typeof DEFAULT_HUB_CONFIG.scheduleItems)
      : DEFAULT_HUB_CONFIG.scheduleItems,
    routineLabels: Array.isArray(raw.routineLabels)
      ? (raw.routineLabels as string[])
      : DEFAULT_HUB_CONFIG.routineLabels,
  };
}

async function getOrCreateHubConfig() {
  let row = await prisma.hubConfig.findUnique({ where: { id: HUB_ID } });
  if (!row) {
    row = await prisma.hubConfig.create({
      data: { id: HUB_ID, config: DEFAULT_HUB_CONFIG },
    });
  }
  return row;
}

// GET /api/hub-config
router.get('/', async (_req, res, next) => {
  try {
    const row = await getOrCreateHubConfig();
    res.json(normalizeConfig(row.config as Record<string, unknown>));
  } catch (err) {
    next(err);
  }
});

// PATCH /api/hub-config
router.patch('/', async (req, res, next) => {
  try {
    const row = await getOrCreateHubConfig();
    const merged = normalizeConfig({
      ...(row.config as Record<string, unknown>),
      ...(req.body as Record<string, unknown>),
    });
    const updated = await prisma.hubConfig.update({
      where: { id: HUB_ID },
      data: { config: merged },
    });
    res.json(normalizeConfig(updated.config as Record<string, unknown>));
  } catch (err) {
    next(err);
  }
});

export default router;
