<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\BaseController;
use App\Core\Request;
use App\Core\Response;
use App\Helpers\AjaxResponse;
use App\Models\AutomationWorkflowModel;
use App\Services\ActivityLogger;

final class AutomationController extends BaseController
{
    public function index(Request $request): Response
    {
        $model = new AutomationWorkflowModel();
        $rows = $model->allWithStepCounts();

        if ($request->isAjax() || $request->isJson()) {
            return AjaxResponse::success($rows);
        }

        return $this->view('marketing/automation', [
            'title' => 'Marketing Automation',
            'activeNav' => 'automation',
            'breadcrumbs' => [['Home', 'dashboard'], ['Marketing', 'campaigns'], ['Automation', 'automation']],
            'rows' => $rows,
        ]);
    }

    public function show(Request $request, array $params): Response
    {
        $model = new AutomationWorkflowModel();
        $id = (int) $params['id'];
        $workflow = $model->find($id);

        if ($workflow === null) {
            return AjaxResponse::notFound('Workflow not found.');
        }

        return AjaxResponse::success([
            'workflow' => $workflow,
            'steps' => $model->steps($id),
            'runs' => $model->runsFor($id),
        ]);
    }

    public function toggleActive(Request $request, array $params): Response
    {
        $model = new AutomationWorkflowModel();
        $id = (int) $params['id'];
        $workflow = $model->find($id);

        if ($workflow === null) {
            return AjaxResponse::notFound('Workflow not found.');
        }

        $newState = (int) $workflow['is_active'] === 1 ? 0 : 1;
        $model->update($id, ['is_active' => $newState], $this->currentUserId());

        ActivityLogger::record(
            'automation_workflow',
            $id,
            $newState ? 'workflow_activated' : 'workflow_deactivated',
            ($newState ? 'Activated' : 'Deactivated') . " automation \"{$workflow['name']}\"",
            category: 'admin'
        );

        return AjaxResponse::success(['is_active' => $newState], 'Automation updated.');
    }
}
