// backend/controllers/assistantController.js
import pool from '../config/db.js';

export const createAssistant = async (req, res) => {
  const { assistant_name } = req.body;
  const user_id = req.userId; // Extracted from auth middleware

  if (!assistant_name) {
    return res.status(400).json({ message: 'Assistant name is required' });
  }

  try {
    const [result] = await pool.execute(
      'INSERT INTO ai_assistants (user_id, assistant_name) VALUES (?, ?)',
      [user_id, assistant_name]
    );
    res.status(201).json({ id: result.insertId, message: 'Assistant created successfully' });
  } catch (error) {
    console.error('Database Error:', error);
    res.status(500).json({ message: 'An unexpected error occurred. Please try again.' });
  }
};

export const getAssistantById = async (req, res) => {
  const { id } = req.params;
  const user_id = req.userId; // comes from auth middleware
  try {
    const [rows] = await pool.execute(
      'SELECT id, assistant_name, created_at FROM ai_assistants WHERE id = ? AND user_id = ?',
      [id, user_id]
    );
    if (rows.length === 0) {
      return res.status(404).json({ message: 'Assistant not found' });
    }
    res.json(rows[0]);
  } catch (error) {
    console.error('Error retrieving assistant:', error);
    res.status(500).json({ message: 'Error retrieving assistant. Please try again later.' });
  }
};

export const getAssistants = async (req, res) => {
  const user_id = req.userId;
  try {
    const [assistants] = await pool.execute(
      'SELECT id, assistant_name, created_at FROM ai_assistants WHERE user_id = ?',
      [user_id]
    );
    res.json(assistants);
  } catch (error) {
    console.error('Database Error:', error);
    res.status(500).json({ message: 'An unexpected error occurred. Please try again.' });
  }
};

export const deleteAssistant = async (req, res) => {
  const { id } = req.params;
  const user_id = req.userId;
  try {
    const [result] = await pool.execute(
      'DELETE FROM ai_assistants WHERE id = ? AND user_id = ?',
      [id, user_id]
    );
    if (result.affectedRows === 0) {
      return res.status(404).json({ message: 'Assistant not found or unauthorized' });
    }
    res.json({ message: 'Assistant deleted successfully' });
  } catch (error) {
    console.error('Database Error:', error);
    res.status(500).json({ message: 'An unexpected error occurred. Please try again.' });
  }
};

export const assignFileToAssistant = async (req, res) => {
  const { assistantId, fileId } = req.params;
  const user_id = req.userId;
  try {
    const [existingAssignment] = await pool.execute(
      'SELECT * FROM assistant_files WHERE assistant_id = ? AND file_id = ?',
      [assistantId, fileId]
    );
    if (existingAssignment.length > 0) {
      return res.status(400).json({ message: 'File is already assigned to this assistant' });
    }
    await pool.execute(
      'INSERT INTO assistant_files (assistant_id, file_id) VALUES (?, ?)',
      [assistantId, fileId]
    );
    res.json({ message: 'File assigned to assistant successfully' });
  } catch (error) {
    console.error('Database Error:', error);
    res.status(500).json({ message: 'An unexpected error occurred. Please try again.' });
  }
};

export const getFilesByAssistant = async (req, res) => {
  const { assistantId } = req.params;
  const user_id = req.userId;
  try {
    const [files] = await pool.execute(
      `SELECT f.id, f.file_name, f.file_path, f.file_type, f.status
       FROM assistant_files af
       JOIN files f ON af.file_id = f.id
       WHERE af.assistant_id = ? AND f.user_id = ?`,
      [assistantId, user_id]
    );
    if (files.length === 0) {
        return res.json([]); // Return an empty array
    }
    res.json(files);
  } catch (error) {
    console.error('Database Error:', error);
    res.status(500).json({ message: 'An unexpected error occurred. Please try again.' });
  }
};

export const assignMultipleFilesToAssistant = async (req, res) => {
  const { assistantId } = req.params;
  const { fileIds } = req.body; // Expect an array of file IDs

  if (!fileIds || !Array.isArray(fileIds) || fileIds.length === 0) {
    return res.status(400).json({ message: 'No files selected' });
  }

  try {
    for (let fileId of fileIds) {
      await pool.execute(
        'INSERT INTO assistant_files (assistant_id, file_id) VALUES (?, ?)',
        [assistantId, fileId]
      );
    }
    res.json({ message: 'Files assigned successfully' });
  } catch (error) {
    console.error('Error assigning files:', error);
    res.status(500).json({ message: 'Database error. Please try again.' });
  }
};

export const removeFileFromAssistant = async (req, res) => {
  const { assistantId, fileId } = req.params;
  try {
    const [result] = await pool.execute(
      'DELETE FROM assistant_files WHERE assistant_id = ? AND file_id = ?',
      [assistantId, fileId]
    );
    if (result.affectedRows === 0) {
      return res.status(404).json({ message: 'File not found in assistant or unauthorized' });
    }
    res.json({ message: 'File removed from assistant successfully' });
  } catch (error) {
    console.error('Database Error:', error);
    res.status(500).json({ message: 'An unexpected error occurred. Please try again.' });
  }
};

