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

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const uploadsDir = process.env.UPLOADS_DIR || path.join(__dirname, '../../uploads');

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

// POST /api/account/name — update (or clear) the authenticated user's display name
router.post('/name', async (req, res) => {
  const { name } = req.body;
  const cleanName = typeof name === 'string' && name.trim() !== '' ? name.trim() : null;
  try {
    await pool.query('UPDATE "user" SET name = $1 WHERE id = $2', [cleanName, req.user!.id]);
    res.json({ name: cleanName });
  } catch {
    res.status(500).json({ error: 'Failed to update name' });
  }
});

// POST /api/account/delete
router.post('/delete', async (req, res) => {
  const userId = req.user!.id;
  const client = await pool.connect();

  try {
    await client.query('BEGIN');

    // 1. Delete all chemicals for this user
    await client.query('DELETE FROM chemicals WHERE user_id = $1', [userId]);

    // 2. Delete all protocols for this user
    await client.query('DELETE FROM protocols WHERE user_id = $1', [userId]);

    // 3. Delete user profile (has CASCADE, but be explicit)
    await client.query('DELETE FROM user_profile WHERE user_id = $1', [userId]);

    // 4. Delete sessions and accounts (CASCADE from user, but be explicit)
    await client.query('DELETE FROM session WHERE "userId" = $1', [userId]);
    await client.query('DELETE FROM account WHERE "userId" = $1', [userId]);
    await client.query('DELETE FROM verification WHERE identifier = $1', [userId]);

    // 5. Delete the user record itself
    await client.query('DELETE FROM "user" WHERE id = $1', [userId]);

    await client.query('COMMIT');

    // 6. Clean up uploaded files outside the transaction
    const userUploadsDir = path.join(uploadsDir, userId);
    if (fs.existsSync(userUploadsDir)) {
      fs.rmSync(userUploadsDir, { recursive: true, force: true });
    }

    res.json({ deleted: true });
  } catch (err) {
    await client.query('ROLLBACK');
    console.error('Account deletion failed:', err);
    res.status(500).json({ error: 'Account deletion failed' });
  } finally {
    client.release();
  }
});

export default router;
