import { Router, Request, Response } from 'express';
import { query } from '../db/client';
import { logger } from '../services/logger';

const router = Router();

/**
 * PATCH /api/profile/team
 * Nutzer setzt sein Team manuell
 */
router.patch('/team', async (req: Request, res: Response): Promise<void> => {
  const userId = req.staffbaseUser!.sub;
  const { team } = req.body as { team: string };

  if (typeof team !== 'string' || team.trim().length === 0) {
    res.status(400).json({ error: 'team darf nicht leer sein' });
    return;
  }

  if (team.trim().length > 80) {
    res.status(400).json({ error: 'team darf maximal 80 Zeichen haben' });
    return;
  }

  try {
    await query(
      `UPDATE users SET team = $1, updated_at = NOW() WHERE id = $2`,
      [team.trim(), userId]
    );
    res.json({ success: true, team: team.trim() });
  } catch (error) {
    logger.error('Failed to update team', { error, userId });
    res.status(500).json({ error: 'Internal server error' });
  }
});

export default router;
