<?php
/**
 * Colex AI - Delete Conversation Endpoint
 *
 * POST /api/colex/delete-conversation
 * Body: { "conversation_id": "..." }
 */

// Ensure this file is accessed through the router
if (!isset($auth) || !isset($db)) {
    http_response_code(500);
    die(json_encode(['error' => 'Direct access not permitted.']));
}

header('Content-Type: application/json');

// Ensure user is authenticated
if (!$auth->isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

$userId = $auth->getUserId();

$input = json_decode(file_get_contents('php://input'), true);
$conversationId = isset($input['conversation_id']) ? $input['conversation_id'] : null;

if (empty($conversationId)) {
    http_response_code(400);
    echo json_encode(['error' => 'Missing conversation_id']);
    exit;
}

try {
    // Verify the conversation exists AND belongs to this user before deleting anything
    $conversation = $db->raw("
        SELECT id
        FROM colex_conversations
        WHERE id = ? AND user_id = ?
    ", [$conversationId, $userId]);

    if (empty($conversation)) {
        http_response_code(404);
        echo json_encode(['error' => 'Not found']);
        exit;
    }

    // Delete dependent messages first
    $db->raw("
        DELETE FROM colex_messages
        WHERE conversation_id = ?
    ", [$conversationId]);

    // Delete the conversation itself, scoped to the owning user as a defense-in-depth check
    $db->raw("
        DELETE FROM colex_conversations
        WHERE id = ? AND user_id = ?
    ", [$conversationId, $userId]);

    echo json_encode(['success' => true]);

} catch (Exception $e) {
    error_log("Error deleting conversation: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['error' => 'Failed to delete conversation']);
}
