<?php
namespace App\Controllers;

use App\Services\AuthService;
use App\Services\DatabaseMaintenanceService;
use App\Services\PaymentRecordsBackfillService;
use App\Services\PaymentTafsiliBackfillService;

class MaintenanceController extends ApiController
{
    private AuthService $authService;
    private DatabaseMaintenanceService $maintenanceService;
    private $app;

    public function __construct(AuthService $authService, DatabaseMaintenanceService $maintenanceService, $app)
    {
        $this->authService = $authService;
        $this->maintenanceService = $maintenanceService;
        $this->app = $app;
    }

    public function dashboard(): void
    {
        $this->ensureAdminOrDelegated('maintenance.admin.view');
        $this->successResponse($this->maintenanceService->dashboard(), 'وضعیت نگهداری دیتابیس آماده است');
    }

    public function listBackups(): void
    {
        $this->ensureAdminOrDelegated('maintenance.admin.view');
        $this->successResponse(['backups' => $this->maintenanceService->listBackups()], 'لیست بکاپ‌ها آماده است');
    }

    public function createBackup(): void
    {
        $this->ensureAdminOrDelegated('maintenance.admin.backup');
        try {
            $label = (string)($_POST['label'] ?? 'manual');
            $backup = $this->maintenanceService->createBackup($label);
            $this->successResponse(['backup' => $backup], 'بکاپ دیتابیس ساخته شد');
        } catch (\Throwable $e) {
            $this->errorResponse($e->getMessage());
        }
    }

    public function restoreBackup(): void
    {
        $this->ensureAdminOrDelegated('maintenance.admin.restore');
        try {
            $filename = (string)($_POST['filename'] ?? '');
            $confirmation = (string)($_POST['confirmation'] ?? '');
            $report = $this->maintenanceService->restoreBackup($filename, $confirmation);
            $this->successResponse(['report' => $report], 'Restore با موفقیت انجام شد');
        } catch (\Throwable $e) {
            $this->errorResponse($e->getMessage());
        }
    }

    public function previewPaymentRecordsBackfill(): void
    {
        $this->ensureAdminOrDelegated('maintenance.admin.backfill.preview');
        $this->sendPaymentRecordsBackfillReport('dry-run');
    }

    public function verifyPaymentRecordsBackfill(): void
    {
        $this->ensureAdminOrDelegated('maintenance.admin.backfill.verify');
        $this->sendPaymentRecordsBackfillReport('verify');
    }

    public function runPaymentRecordsBackfill(): void
    {
        $this->ensureAdminOrDelegated('maintenance.admin.backfill.run');
        if ((string)($_POST['confirmation'] ?? '') !== 'RUN_BACKFILL') {
            $this->errorResponse('برای اجرای backfill عبارت RUN_BACKFILL الزامی است');
        }

        try {
            $backup = $this->maintenanceService->createBackup('pre-backfill-payment-records');
            $report = $this->executePaymentRecordsBackfill('run');
            $this->successResponse([
                'backup' => $backup,
                'report' => $report,
            ], 'Backfill اجرا شد');
        } catch (\Throwable $e) {
            $this->errorResponse($e->getMessage());
        }
    }

    public function previewPaymentTafsiliBackfill(): void
    {
        $this->ensureAdminOrDelegated('maintenance.admin.backfill.preview');
        $this->sendPaymentTafsiliBackfillReport('dry-run');
    }

    public function verifyPaymentTafsiliBackfill(): void
    {
        $this->ensureAdminOrDelegated('maintenance.admin.backfill.verify');
        $this->sendPaymentTafsiliBackfillReport('verify');
    }

    public function runPaymentTafsiliBackfill(): void
    {
        $this->ensureAdminOrDelegated('maintenance.admin.backfill.run');
        if ((string)($_POST['confirmation'] ?? '') !== 'RUN_TAFSILI_BACKFILL') {
            $this->errorResponse('برای اجرای backfill عبارت RUN_TAFSILI_BACKFILL الزامی است');
        }

        try {
            $backup = $this->maintenanceService->createBackup('pre-backfill-payment-tafsili');
            $report = $this->executePaymentTafsiliBackfill('run');
            $this->successResponse([
                'backup' => $backup,
                'report' => $report,
            ], 'Backfill کد تفصیلی اجرا شد');
        } catch (\Throwable $e) {
            $this->errorResponse($e->getMessage());
        }
    }

    private function sendPaymentRecordsBackfillReport(string $mode): void
    {
        try {
            $report = $this->executePaymentRecordsBackfill($mode);
            $this->successResponse(['report' => $report], 'گزارش backfill آماده است');
        } catch (\Throwable $e) {
            $this->errorResponse($e->getMessage());
        }
    }

    private function executePaymentRecordsBackfill(string $mode): array
    {
        $limit = max(0, (int)($_POST['limit'] ?? 0));
        $backfill = new PaymentRecordsBackfillService($this->app, $mode, $limit);
        return $backfill->execute();
    }

    private function sendPaymentTafsiliBackfillReport(string $mode): void
    {
        try {
            $report = $this->executePaymentTafsiliBackfill($mode);
            $this->successResponse(['report' => $report], 'گزارش backfill کد تفصیلی آماده است');
        } catch (\Throwable $e) {
            $this->errorResponse($e->getMessage());
        }
    }

    private function executePaymentTafsiliBackfill(string $mode): array
    {
        $limit = max(0, (int)($_POST['limit'] ?? 0));
        $backfill = new PaymentTafsiliBackfillService($this->app->db, $mode, $limit);
        return $backfill->execute();
    }

    private function ensureAdminOrDelegated(string $capabilityKey): void
    {
        if (!$this->authService->isAdmin() && !$this->hasDelegatedCapability($capabilityKey)) {
            $this->errorResponse('فقط مدیر سیستم به صفحه نگهداری دیتابیس دسترسی دارد');
        }
    }
}
