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

const router = Router();

router.get('/', requireAuth, async (req, res) => {
  try {
    const result = await pool.query(
      'SELECT * FROM user_profile WHERE user_id = $1',
      [req.user!.id]
    );
    if (result.rows.length === 0) {
      return res.status(404).json({ error: 'Profile not found' });
    }
    res.json(result.rows[0]);
  } catch {
    res.status(500).json({ error: 'Server error' });
  }
});

router.post('/', requireAuth, async (req, res) => {
  const { pi_first_name, bldg_code, lab, contact } = req.body;
  // Coerce empty strings to null so the DB stores a clean null rather than "".
  const toNull = (v: unknown) => (typeof v === 'string' && v.trim() !== '' ? v.trim() : null);
  try {
    const result = await pool.query(
      `INSERT INTO user_profile (user_id, pi_first_name, bldg_code, lab, contact)
       VALUES ($1, $2, $3, $4, $5)
       ON CONFLICT (user_id) DO UPDATE SET
         pi_first_name = EXCLUDED.pi_first_name,
         bldg_code = EXCLUDED.bldg_code,
         lab = EXCLUDED.lab,
         contact = EXCLUDED.contact,
         updated_at = NOW()
       RETURNING *`,
      [req.user!.id, toNull(pi_first_name), toNull(bldg_code), toNull(lab), toNull(contact)]
    );
    res.json(result.rows[0]);
  } catch {
    res.status(500).json({ error: 'Server error' });
  }
});

export default router;
