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

const router = Router();

const DEFAULTS: Record<string, { title: string; titleEn: string; subtitle: string }> = {
  HR: {
    title:    'HR 부문',
    titleEn:  'Human Resources',
    subtitle: '임직원의 몰입(Engagement)과 성장(Education)',
  },
  '운영관리': {
    title:    '총무관리',
    titleEn:  'GA',
    subtitle: '인프라 고도화와 자산 라이프사이클 표준화',
  },
};

// GET /api/columns/:key
router.get('/:key', async (req, res, next) => {
  try {
    const { key } = req.params;
    let config = await prisma.columnConfig.findUnique({ where: { key } });

    if (!config) {
      const def = DEFAULTS[key];
      config = await prisma.columnConfig.create({
        data: { key, title: def?.title ?? key, titleEn: def?.titleEn ?? '', subtitle: def?.subtitle ?? '' },
      });
    } else if (key === '운영관리') {
      const legacyTitles = ['운영관리', '운영관리 부문'];
      const legacyTitleEn = ['Operations'];
      if (legacyTitles.includes(config.title) || legacyTitleEn.includes(config.titleEn)) {
        config = await prisma.columnConfig.update({
          where: { key },
          data: {
            title: DEFAULTS[key]?.title ?? config.title,
            titleEn: DEFAULTS[key]?.titleEn ?? config.titleEn,
          },
        });
      }
    }

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

// PATCH /api/columns/:key
router.patch('/:key', async (req, res, next) => {
  try {
    const { key } = req.params;
    const { title, titleEn, subtitle, cardOrder } = req.body as Record<string, string>;

    const config = await prisma.columnConfig.upsert({
      where: { key },
      create: {
        key,
        title:     title    ?? DEFAULTS[key]?.title    ?? key,
        titleEn:   titleEn  ?? DEFAULTS[key]?.titleEn  ?? '',
        subtitle:  subtitle ?? DEFAULTS[key]?.subtitle ?? '',
        cardOrder: cardOrder ?? null,
      },
      update: {
        ...(title     !== undefined && { title }),
        ...(titleEn   !== undefined && { titleEn }),
        ...(subtitle  !== undefined && { subtitle }),
        ...(cardOrder !== undefined && { cardOrder }),
      },
    });

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

export default router;
