<?php
namespace App\Controllers;

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

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->ensureAdmin();
        $this->successResponse($this->maintenanceService->dashboard(), 'وضعیت نگهداری دیتابیس آماده است');
    }

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

    public function createBackup(): void
    {
        $this->ensureAdmin();
        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->ensureAdmin();
        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->ensureAdmin();
        $this->sendPaymentRecordsBackfillReport('dry-run');
    }

    public function verifyPaymentRecordsBackfill(): void
    {
        $this->ensureAdmin();
        $this->sendPaymentRecordsBackfillReport('verify');
    }

    public function runPaymentRecordsBackfill(): void
    {
        $this->ensureAdmin();
        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());
        }
    }

    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 ensureAdmin(): void
    {
        if (!$this->authService->isAdmin()) {
            $this->errorResponse('فقط مدیر سیستم به صفحه نگهداری دیتابیس دسترسی دارد');
        }
    }
}
