import { Router } from 'express';
import { pool } from '../db/pool.js';
import { requireAuth } from '../auth/middleware.js';
import multer from 'multer';
import path from 'path';
import fs from 'fs';
import { fileURLToPath } from 'url';
import { analyzeProtocolWithOpenAI } from '../ai/protocolAnalysis.js';

const __dirname = path.dirname(fileURLToPath(import.meta.url));

const router = Router();
router.use(requireAuth);

const uploadsDir = process.env.UPLOADS_DIR || path.join(__dirname, '../../uploads');
fs.mkdirSync(uploadsDir, { recursive: true });

const storage = multer.diskStorage({
  destination: (req, _file, cb) => {
    const userDir = path.join(uploadsDir, (req as any).user.id);
    fs.mkdirSync(userDir, { recursive: true });
    cb(null, userDir);
  },
  filename: (_req, file, cb) => {
    const unique = `${Date.now()}-${Math.round(Math.random() * 1e9)}`;
    cb(null, `${unique}${path.extname(file.originalname)}`);
  },
});

const upload = multer({
  storage,
  limits: { fileSize: 10 * 1024 * 1024 },
  fileFilter: (_req, file, cb) => {
    const allowed = ['.pdf', '.doc', '.docx', '.txt'];
    if (allowed.includes(path.extname(file.originalname).toLowerCase())) {
      cb(null, true);
    } else {
      cb(new Error('Only PDF, DOC, DOCX, TXT files allowed'));
    }
  },
});

// GET /api/protocols
router.get('/', async (req, res) => {
  try {
    const result = await pool.query(
      'SELECT * FROM protocols WHERE user_id = $1 ORDER BY created_at DESC',
      [req.user!.id]
    );
    res.json(result.rows);
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: 'Internal server error' });
  }
});

// POST /api/protocols
router.post('/', upload.single('file'), async (req, res) => {
  try {
    const { title, content } = req.body;
    const userId = (req as any).user.id;
    const fileUrl = req.file ? `/uploads/${userId}/${req.file.filename}` : null;

    const result = await pool.query(
      `INSERT INTO protocols (user_id, title, content, file_url)
       VALUES ($1, $2, $3, $4) RETURNING *`,
      [req.user!.id, title || 'Untitled Protocol', content || '', fileUrl]
    );
    res.status(201).json(result.rows[0]);
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: 'Internal server error' });
  }
});

// PATCH /api/protocols/:id/analysis
router.patch('/:id/analysis', async (req, res) => {
  try {
    const { analysis_results } = req.body;
    const result = await pool.query(
      `UPDATE protocols SET analysis_results = $1::jsonb, updated_at = NOW()
       WHERE id = $2 AND user_id = $3 RETURNING *`,
      [JSON.stringify(analysis_results), req.params.id, req.user!.id]
    );
    if (result.rows.length === 0) return res.status(404).json({ error: 'Not found' });
    res.json(result.rows[0]);
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: 'Internal server error' });
  }
});

// POST /api/protocols/:id/analyze
router.post('/:id/analyze', async (req, res) => {
  try {
    const protocol = await pool.query(
      'SELECT * FROM protocols WHERE id = $1 AND user_id = $2',
      [req.params.id, req.user!.id]
    );
    if (protocol.rows.length === 0) return res.status(404).json({ error: 'Not found' });

    const content = protocol.rows[0].content;
    if (!content || !content.trim()) {
      return res.status(400).json({ error: 'Protocol content is required before analysis' });
    }

    const analysisResults = await analyzeProtocolWithOpenAI(content);
    const result = await pool.query(
      `UPDATE protocols SET analysis_results = $1::jsonb, updated_at = NOW()
       WHERE id = $2 AND user_id = $3 RETURNING *`,
      [JSON.stringify(analysisResults), req.params.id, req.user!.id]
    );

    res.json(result.rows[0]);
  } catch (err) {
    console.error(err);
    const message = err instanceof Error ? err.message : 'Protocol analysis failed';
    const status = message.includes('OPENAI_API_KEY') ? 500 : 502;
    res.status(status).json({ error: message });
  }
});

// DELETE /api/protocols/:id
router.delete('/:id', async (req, res) => {
  try {
    const result = await pool.query(
      'DELETE FROM protocols WHERE id = $1 AND user_id = $2 RETURNING file_url',
      [req.params.id, req.user!.id]
    );
    const fileUrl = result.rows[0]?.file_url;
    if (fileUrl) {
      // fileUrl is like /uploads/<userId>/<filename>
      const relative = fileUrl.replace(/^\/uploads\//, '');
      const filePath = path.join(uploadsDir, relative);
      fs.rmSync(filePath, { force: true });
    }
    res.status(204).end();
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: 'Internal server error' });
  }
});

export default router;
