<?php
/**
 * Configuration Controller for Caterpoint Module
 *
 * @category    PortalPeople
 * @package     Caterpoint
 * @author      Portal People Development Team
 * @copyright   Copyright (c) 2026 Portal People (https://portalpeople.co.uk)
 */

namespace PortalPeople\caterpoint\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use yii\web\Controller;
use yii\web\Response;
use yii\widgets\ActiveForm;
use PortalPeople\caterpoint\Module;
use PortalPeople\caterpoint\models\ConfigForm;

/**
 * Configuration Controller
 *
 * Handles Caterpoint module setup through web interface.
 */
class ConfigController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    'validate' => ['POST'],
                    'test-connection' => ['POST'],
                    'import' => ['POST'],
                    'save' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Display setup form.
     *
     * @return string|Response
     */
    public function actionIndex()
    {
        $model = new ConfigForm();
        $model->loadFromParams();

        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->saveToParams()) {
                Yii::$app->session->setFlash('success', 'Caterpoint setup saved successfully.');
                return $this->refresh();
            }

            Yii::$app->session->setFlash('error', 'Failed to save Caterpoint setup. Check params-local.php permissions.');
        }

        return $this->render('index', [
            'model' => $model,
        ]);
    }

    /**
     * AJAX validation endpoint.
     *
     * @return array
     */
    public function actionValidate()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        $model = new ConfigForm();
        $model->loadFromParams();

        if ($model->load(Yii::$app->request->post())) {
            return ActiveForm::validate($model);
        }

        return [];
    }

    /**
     * Test Caterpoint API connection with submitted setup fields.
     *
     * @return array
     */
    public function actionTestConnection(): array
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        $model = new ConfigForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            return $model->testConnection();
        }

        return [
            'success' => false,
            'message' => 'Invalid setup data.',
            'errors' => $model->errors,
        ];
    }

    /**
     * Get current module/setup status.
     *
     * @return array
     */
    public function actionStatus(): array
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        try {
            $module = Yii::$app->getModule('caterpoint');
            $configured = $module instanceof Module ? $module->isConfigured() : false;
            $cursor = null;

            if ($module instanceof Module) {
                try {
                    $service = $module->createOrderImportService();
                    $cursor = $service->cursorStore->get();
                } catch (\Throwable $throwable) {
                }
            }

            return [
                'success' => true,
                'configured' => $configured,
                'cursor' => $cursor,
            ];
        } catch (\Throwable $throwable) {
            return [
                'success' => false,
                'message' => 'Failed to load setup status: ' . $throwable->getMessage(),
            ];
        }
    }

    /**
     * Trigger manual import from setup screen.
     *
     * @return array
     */
    public function actionImport(): array
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        try {
            $module = Yii::$app->getModule('caterpoint');
            if (!$module instanceof Module) {
                return [
                    'success' => false,
                    'message' => 'Caterpoint module not available.',
                ];
            }

            if (!$module->isConfigured()) {
                return [
                    'success' => false,
                    'message' => 'Caterpoint setup is incomplete. Save endpoint and token first.',
                ];
            }

            $limit = (int) Yii::$app->request->post('limit', 0);
            $dryRun = (bool) Yii::$app->request->post('dryRun', true);

            $service = $module->createOrderImportService();
            $result = $service->run(null, $limit, $dryRun);

            return [
                'success' => true,
                'message' => $dryRun ? 'Dry-run import completed.' : 'Import completed.',
                'result' => $result,
            ];
        } catch (\Throwable $throwable) {
            return [
                'success' => false,
                'message' => 'Import failed: ' . $throwable->getMessage(),
            ];
        }
    }

    /**
     * Export current setup (token masked).
     *
     * @return array
     */
    public function actionExport(): array
    {
        $model = new ConfigForm();
        $model->loadFromParams();

        Yii::$app->response->format = Response::FORMAT_JSON;
        Yii::$app->response->headers->set('Content-Disposition', 'attachment; filename="caterpoint-config.json"');

        return $model->exportConfig();
    }

    /**
     * Reset setup to defaults.
     *
     * @return Response
     */
    public function actionReset(): Response
    {
        try {
            $model = new ConfigForm();
            if ($model->resetToDefaults()) {
                Yii::$app->session->setFlash('success', 'Caterpoint setup reset to defaults.');
            } else {
                Yii::$app->session->setFlash('error', 'Failed to reset Caterpoint setup.');
            }
        } catch (\Throwable $throwable) {
            Yii::$app->session->setFlash('error', 'Error resetting setup: ' . $throwable->getMessage());
        }

        return $this->redirect(['index']);
    }
}
