const router = require('express').Router();
const prisma = require('../lib/prisma');

// GET /api/daily-statuses/:statusId/analyses
router.get('/daily-statuses/:statusId/analyses', async (req, res, next) => {
  try {
    const analyses = await prisma.dailyAnalysis.findMany({
      where: { daily_status_id: req.params.statusId },
      orderBy: { created_at: 'desc' },
      select: {
        id: true,
        created_at: true,
        file_name: true,
        timestamp_col: true,
        note_col: true,
        classifications: true,
        total_note_rows: true,
        session_end_ts: true,
        category_counts: true,
        consecutive_stats: true,
        runs: true,
        // sequence omitted from list — fetch individually when needed
      },
    });
    res.json(analyses);
  } catch (err) { next(err); }
});

// POST /api/daily-statuses/:statusId/analyses
router.post('/daily-statuses/:statusId/analyses', async (req, res, next) => {
  try {
    const status = await prisma.dailyStatus.findUnique({ where: { id: req.params.statusId } });
    if (!status) return res.status(404).json({ error: 'Daily status not found' });

    const { file_name, timestamp_col, note_col, classifications, total_note_rows,
            session_end_ts, sequence, category_counts, consecutive_stats, runs } = req.body;

    if (!timestamp_col || !note_col || classifications == null || total_note_rows == null
        || !sequence || !category_counts || !consecutive_stats || !runs) {
      return res.status(422).json({ error: 'Missing required analysis fields' });
    }

    const analysis = await prisma.dailyAnalysis.create({
      data: {
        daily_status_id:   req.params.statusId,
        file_name:         file_name ?? null,
        timestamp_col,
        note_col,
        classifications,
        total_note_rows,
        session_end_ts:    session_end_ts != null ? Number(session_end_ts) : null,
        sequence,
        category_counts,
        consecutive_stats,
        runs,
      },
    });
    res.status(201).json(analysis);
  } catch (err) { next(err); }
});

// GET /api/analyses/:id  (full record including sequence)
router.get('/analyses/:id', async (req, res, next) => {
  try {
    const analysis = await prisma.dailyAnalysis.findUnique({ where: { id: req.params.id } });
    if (!analysis) return res.status(404).json({ error: 'Analysis not found' });
    res.json(analysis);
  } catch (err) { next(err); }
});

// DELETE /api/analyses/:id
router.delete('/analyses/:id', async (req, res, next) => {
  try {
    await prisma.dailyAnalysis.delete({ where: { id: req.params.id } });
    res.status(204).send();
  } catch (err) { next(err); }
});

module.exports = router;
