<?php

namespace App\Support;

use App\Models\AdminUser;
use App\Models\ReportJob;
use Illuminate\Database\Eloquent\Builder;

/** 报表导出任务的所有权与报表类型能力门禁。 */
final class AdminReportJobPolicy
{
    /**
     * @param  Builder<ReportJob>  $query
     */
    public static function applyToJobsQuery(Builder $query, AdminUser $admin): void
    {
        if ($admin->isSuperAdmin()) {
            return;
        }

        $query->where('admin_user_id', (int) $admin->getKey());
    }

    public static function jobAccessible(AdminUser $admin, ReportJob $job): bool
    {
        if ($admin->isSuperAdmin()) {
            return true;
        }

        return $job->admin_user_id !== null
            && (int) $job->admin_user_id === (int) $admin->getKey();
    }

    public static function canExportReportType(AdminUser $admin, string $reportType): bool
    {
        if (! $admin->hasPermissionCode('service.report.export')) {
            return false;
        }

        return match ($reportType) {
            'audit_operation_report' => $admin->hasPermissionCode('service.audit.view'),
            // 风险池没有可靠的站点归属快照；在可证明隔离前只允许全局超管导出。
            'hot_number_risk_report', 'sold_out_number_report' => $admin->isSuperAdmin()
                && $admin->hasPermissionCode('risk.monitor.view'),
            default => true,
        };
    }
}
