import { Router } from 'express';
import { prisma } from '../lib/prisma';
import { AppError } from '../middleware/errorHandler';
import { uploadTeamPhoto } from '../middleware/uploadTeamPhoto';
import { cleanupUploadedFile, DISK_FULL_MESSAGE, isDiskFullError } from '../lib/uploadErrors';

const router = Router();

const memberSelect = {
  id: true,
  name: true,
  rank: true,
  role: true,
  cell: true,
  contact: true,
  photoUrl: true,
  sortOrder: true,
  isActive: true,
};

// GET /api/team-members  (?all=1 이면 비활성 포함 — 관리 화면용)
router.get('/', async (req, res, next) => {
  try {
    const includeAll = req.query.all === '1' || req.query.all === 'true';
    const members = await prisma.teamMember.findMany({
      where: includeAll ? undefined : { isActive: true },
      select: memberSelect,
      orderBy: [{ sortOrder: 'asc' }, { name: 'asc' }],
    });
    res.json(members);
  } catch (err) {
    next(err);
  }
});

// POST /api/team-members/photo — 팀원 사진 (로컬 uploads/team/ 저장)
router.post('/photo', uploadTeamPhoto.single('photo'), async (req, res, next) => {
  try {
    if (!req.file) {
      throw new AppError(400, '이미지 파일을 선택해 주세요.');
    }
    res.status(201).json({
      url: `/uploads/team/${req.file.filename}`,
      filename: req.file.filename,
    });
  } catch (err) {
    if (isDiskFullError(err)) {
      cleanupUploadedFile(req.file);
      next(new AppError(507, DISK_FULL_MESSAGE));
      return;
    }
    next(err);
  }
});

// POST /api/team-members — 인원 등록
router.post('/', async (req, res, next) => {
  try {
    const { name, rank, role, cell, contact, photoUrl, sortOrder } =
      req.body as Record<string, unknown>;

    if (!name || typeof name !== 'string' || !name.trim()) {
      throw new AppError(400, '이름은 필수입니다.');
    }

    const member = await prisma.teamMember.create({
      data: {
        name: name.trim(),
        rank: typeof rank === 'string' ? rank : null,
        role: typeof role === 'string' ? role : null,
        cell: typeof cell === 'string' ? cell : null,
        contact: typeof contact === 'string' ? contact : null,
        photoUrl: typeof photoUrl === 'string' ? photoUrl : null,
        sortOrder: typeof sortOrder === 'number' ? sortOrder : Number(sortOrder) || 0,
      },
      select: memberSelect,
    });

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

// PATCH /api/team-members/:id
router.patch('/:id', async (req, res, next) => {
  try {
    const existing = await prisma.teamMember.findUnique({ where: { id: req.params.id } });
    if (!existing) throw new AppError(404, '팀원을 찾을 수 없습니다.');

    const { name, rank, role, cell, contact, photoUrl, sortOrder, isActive } =
      req.body as Record<string, unknown>;

    const member = await prisma.teamMember.update({
      where: { id: req.params.id },
      data: {
        ...(name !== undefined && { name: String(name).trim() }),
        ...(rank !== undefined && { rank: rank ? String(rank) : null }),
        ...(role !== undefined && { role: role ? String(role) : null }),
        ...(cell !== undefined && { cell: cell ? String(cell) : null }),
        ...(contact !== undefined && { contact: contact ? String(contact) : null }),
        ...(photoUrl !== undefined && { photoUrl: photoUrl ? String(photoUrl) : null }),
        ...(sortOrder !== undefined && { sortOrder: Number(sortOrder) || 0 }),
        ...(isActive !== undefined && { isActive: isActive === true || isActive === 'true' }),
      },
      select: memberSelect,
    });

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

// DELETE /api/team-members/:id — soft delete
router.delete('/:id', async (req, res, next) => {
  try {
    const existing = await prisma.teamMember.findUnique({ where: { id: req.params.id } });
    if (!existing) throw new AppError(404, '팀원을 찾을 수 없습니다.');

    await prisma.teamMember.update({
      where: { id: req.params.id },
      data: { isActive: false },
    });

    res.status(204).send();
  } catch (err) {
    next(err);
  }
});

export default router;
