import { Router } from 'express';
import { db } from '../db.js';
import { authRequired } from '../middleware/auth.js';

export const profileRouter = Router();
profileRouter.use(authRequired);

// GET /api/profile — профиль текущего пользователя
profileRouter.get('/', (req, res) => {
  const profile = db.prepare(
    'SELECT full_name, company, position, signature FROM profiles WHERE user_id = ?'
  ).get(req.user.id);
  res.json({ profile: profile || { full_name: '', company: '', position: '', signature: '' } });
});

// PUT /api/profile — сохранить профиль текущего пользователя
profileRouter.put('/', (req, res) => {
  const full_name = String(req.body?.full_name || '').slice(0, 200);
  const company = String(req.body?.company || '').slice(0, 200);
  const position = String(req.body?.position || '').slice(0, 200);
  const signature = String(req.body?.signature || '').slice(0, 2000);

  db.prepare(`
    INSERT INTO profiles (user_id, full_name, company, position, signature)
    VALUES (@id, @full_name, @company, @position, @signature)
    ON CONFLICT(user_id) DO UPDATE SET
      full_name = excluded.full_name,
      company   = excluded.company,
      position  = excluded.position,
      signature = excluded.signature
  `).run({ id: req.user.id, full_name, company, position, signature });

  res.json({ ok: true });
});
