<?php

namespace EasyLinkAutomations\HTTP\Controllers;

if (!defined('ABSPATH')) {
    exit;
}

use EasyLinkAutomations\HTTP\Request\Request;
use EasyLinkAutomations\HTTP\Response;
use EasyLinkAutomations\Models\ExecutionLog;

/**
 * Handles execution log endpoints.
 */
final class LogController
{
    /**
     * Paginated log listing with filters.
     */
    public function index(Request $request): Response
    {
        $filters = [
            'page'          => (int) ($request->get('page') ?? 1),
            'per_page'      => (int) ($request->get('per_page') ?? 20),
            'status'        => $request->get('status') ?? '',
            'automation_id' => (int) ($request->get('automation_id') ?? 0),
            'search'        => $request->get('search') ?? '',
        ];

        $logs        = ExecutionLog::paginateFiltered($filters);
        $automations = ExecutionLog::automationsForFilter();

        return Response::success([
            'logs'        => $logs,
            'automations' => $automations,
        ]);
    }

    /**
     * Single log detail.
     */
    public function show(Request $request): Response
    {
        $id = (int) $request->get('log_id');
        if (!$id) {
            return Response::error(__('Log ID is required', 'easylink-automations'));
        }

        $log = ExecutionLog::find($id);
        if (!$log) {
            return Response::error('Log entry not found', 404);
        }

        return Response::success(['log' => $log]);
    }

    /**
     * Delete a single log entry.
     */
    public function destroy(Request $request): Response
    {
        $id = (int) $request->get('log_id');
        if (!$id) {
            return Response::error(__('Log ID is required', 'easylink-automations'));
        }

        $deleted = ExecutionLog::delete($id);

        return $deleted
            ? Response::success(['deleted' => true])
            : Response::error(__('Failed to delete log entry', 'easylink-automations'));
    }

    /**
     * Clear all logs, optionally for a specific automation.
     */
    public function clear(Request $request): Response
    {
        $automationId = (int) ($request->get('automation_id') ?? 0);
        $deleted = ExecutionLog::deleteAll($automationId ?: null);

        return Response::success(['deleted_count' => $deleted]);
    }
}
