/**
 * routes/takedownNotes.js
 *
 * Operator notes on a takedown. Distinct from the audit_log:
 * audit_log = system events ("email sent at 14:32"); takedown_notes =
 * operator commentary ("called the platform rep, promised takedown
 * by Friday"). Lawyer-defensibility 6 months later.
 *
 * Superadmin-only writes (the same person who can manual-probe).
 * Read access = owner of the takedown OR superadmin.
 */

'use strict';

const express = require('express');
const router = express.Router();
const { requireLogin } = require('../middleware/auth');
const Takedown = require('../models/takedown');
const Notes = require('../models/takedownNote');
const Audit = require('../models/auditLog');
const { db } = require('../config/db');
const { sendUserError } = require('../middleware/userErrors');

function userCanReadTakedown(user, td) {
  if (!td) return false;
  if (user.role === 'superadmin') return true;
  return td.user_id === user.id;
}

// GET /takedown/:id/notes — list all notes for a takedown
router.get('/takedown/:id/notes', requireLogin, (req, res) => {
  const td = Takedown.getById(parseInt(req.params.id, 10));
  if (!userCanReadTakedown(req.user, td)) {
    return res.status(403).json({ error: 'FORBIDDEN' });
  }
  const notes = Notes.listForTakedown(td.id);
  res.json({ notes, count: notes.length });
});

// POST /takedown/:id/notes — add a note. Superadmin-only writes.
router.post('/takedown/:id/notes', requireLogin, (req, res) => {
  if (req.user.role !== 'superadmin') {
    return res.status(403).json({ error: 'FORBIDDEN', message: 'Operator notes are superadmin-only.' });
  }
  const td = Takedown.getById(parseInt(req.params.id, 10));
  if (!td) return res.status(404).json({ error: 'NOT_FOUND' });
  const body = (req.body && typeof req.body.body === 'string') ? req.body.body.trim() : '';
  if (!body) return res.status(400).json({ error: 'EMPTY_BODY', message: 'Note body is required.' });
  if (body.length > 4000) return res.status(400).json({ error: 'TOO_LONG', message: 'Note must be ≤4000 chars.' });
  const note = Notes.create({ takedown_id: td.id, user_id: req.user.id, body });
  try {
    Audit.log(req.user, 'takedown.note.add', `takedown:${td.id}`, {
      note_id: note.id, body_preview: body.slice(0, 80),
    });
  } catch (_) { /* best-effort */ }
  res.json({ ok: true, note });
});

// PATCH /takedown/notes/:noteId — edit your own note (or any if superadmin).
router.patch('/takedown/notes/:noteId', requireLogin, (req, res) => {
  const note = Notes.getById(parseInt(req.params.noteId, 10));
  if (!note) return res.status(404).json({ error: 'NOT_FOUND' });
  if (req.user.role !== 'superadmin' && note.user_id !== req.user.id) {
    return res.status(403).json({ error: 'FORBIDDEN' });
  }
  const body = (req.body && typeof req.body.body === 'string') ? req.body.body.trim() : '';
  if (!body) return res.status(400).json({ error: 'EMPTY_BODY' });
  if (body.length > 4000) return res.status(400).json({ error: 'TOO_LONG' });
  const updated = Notes.update(note.id, body);
  try {
    Audit.log(req.user, 'takedown.note.edit', `takedown:${note.takedown_id}`, { note_id: note.id });
  } catch (_) {}
  res.json({ ok: true, note: updated });
});

// DELETE /takedown/notes/:noteId — delete a note. Superadmin-only.
router.delete('/takedown/notes/:noteId', requireLogin, (req, res) => {
  if (req.user.role !== 'superadmin') {
    return res.status(403).json({ error: 'FORBIDDEN', message: 'Deleting notes is superadmin-only.' });
  }
  const note = Notes.getById(parseInt(req.params.noteId, 10));
  if (!note) return res.status(404).json({ error: 'NOT_FOUND' });
  Notes.remove(note.id);
  try {
    Audit.log(req.user, 'takedown.note.delete', `takedown:${note.takedown_id}`, { note_id: note.id });
  } catch (_) {}
  res.json({ ok: true });
});

// GET /takedown/notes-counts?ids=1,2,3 — batch count for the dashboard table.
// Lets the dashboard render a "Notes (3)" badge per row without 50 requests.
router.get('/takedown/notes-counts', requireLogin, (req, res) => {
  const ids = String(req.query.ids || '').split(',').map(s => parseInt(s, 10)).filter(Boolean);
  if (!ids.length) return res.json({ counts: {} });
  if (ids.length > 500) return res.status(400).json({ error: 'TOO_MANY_IDS', message: '500 max.' });
  const placeholders = ids.map(() => '?').join(',');
  const rows = db.prepare(`
    SELECT takedown_id, COUNT(*) AS n
      FROM takedown_notes
     WHERE takedown_id IN (${placeholders})
     GROUP BY takedown_id
  `).all(...ids);
  const counts = {};
  for (const r of rows) counts[r.takedown_id] = r.n;
  res.json({ counts });
});

module.exports = router;