// Member profile updates (display name, bio, avatar).
import { Router } from 'express';
import { z } from 'zod';
import { execute, queryOne } from '../db/client.js';
import { requireAuth } from '../middleware/auth.js';
import { HttpError } from '../middleware/error.js';

const router = Router();
const now = () => Math.floor(Date.now() / 1000);

const updateSchema = z
  .object({
    display_name: z.string().min(1).max(80).optional(),
    bio: z.string().max(1000).optional(),
    avatar_url: z.string().url().max(500).optional(),
  })
  .refine((d) => Object.keys(d).length > 0, { message: 'Nothing to update' });

router.patch('/profile', requireAuth, async (req, res, next) => {
  try {
    const data = updateSchema.parse(req.body);
    const fields = [];
    const args = [];
    for (const key of ['display_name', 'bio', 'avatar_url']) {
      if (data[key] !== undefined) {
        fields.push(`${key} = ?`);
        args.push(data[key]);
      }
    }
    fields.push('updated_at = ?');
    args.push(now());
    args.push(req.auth.userId);
    await execute(`UPDATE users SET ${fields.join(', ')} WHERE id = ?`, args);
    const user = await queryOne(
      `SELECT id, email, display_name, role, avatar_url, bio FROM users WHERE id = ?`,
      [req.auth.userId]
    );
    res.json({ user });
  } catch (err) {
    if (err instanceof z.ZodError) {
      return next(new HttpError(400, 'invalid_input', err.issues[0]?.message || 'Invalid input'));
    }
    next(err);
  }
});

export default router;
