<?php
namespace App\Controllers;

use App\Services\ActivityTypeRepairService;
use App\Services\AuthService;
use RuntimeException;

class ActivityRepairController extends ApiController
{
    private AuthService $authService;
    private ActivityTypeRepairService $repairService;

    public function __construct(AuthService $authService, ActivityTypeRepairService $repairService)
    {
        $this->authService = $authService;
        $this->repairService = $repairService;
    }

    public function preview(): void
    {
        $this->ensureAdmin();
        $backupPath = $this->resolveBackupPath();
        $report = $this->repairService->preview($backupPath);
        $this->successResponse(['report' => $report], 'پیش‌نمایش بازسازی نوع فعالیت آماده است');
    }

    public function run(): void
    {
        $this->ensureAdmin();
        $backupPath = $this->resolveBackupPath();
        $report = $this->repairService->apply($backupPath);
        $this->successResponse(['report' => $report], 'بازسازی نوع فعالیت اجرا شد');
    }

    private function ensureAdmin(): void
    {
        if (!$this->authService->isAdmin()) {
            $this->errorResponse('فقط مدیر می‌تواند این عملیات را اجرا کند', 403);
        }
    }

    private function resolveBackupPath(): string
    {
        $projectRoot = realpath(dirname(__DIR__, 2));
        $input = trim((string)($_POST['backup_path'] ?? $_GET['backup_path'] ?? ''));
        $candidate = $input !== '' ? $input : 'latest db backup.sql';

        if ($projectRoot === false) {
            throw new RuntimeException('Project root not found');
        }

        if ($candidate === '') {
            $candidate = 'latest db backup.sql';
        }

        if (!$this->isAbsolutePath($candidate)) {
            $candidate = $projectRoot . DIRECTORY_SEPARATOR . ltrim(str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $candidate), DIRECTORY_SEPARATOR);
        }

        $real = realpath($candidate);
        if ($real === false || !is_file($real)) {
            $this->errorResponse('فایل بکاپ پیدا نشد: ' . basename($candidate), 404);
        }

        if (strpos($real, $projectRoot) !== 0) {
            $this->errorResponse('مسیر فایل بکاپ مجاز نیست', 400);
        }

        return $real;
    }

    private function isAbsolutePath(string $path): bool
    {
        return preg_match('/^(?:[A-Za-z]:\\\\|\/)/', $path) === 1;
    }
}
