<?php

declare(strict_types=1);

namespace ImovelZapAi\SuperAdmin\Infrastructure\Http\Controllers\Api;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use ImovelZapAi\SuperAdmin\Application\Actions\PlatformChangeTenantStatusAction;
use ImovelZapAi\SuperAdmin\Application\Actions\PlatformCreateTenantAction;
use ImovelZapAi\SuperAdmin\Application\Queries\GetPlatformMetricsQuery;
use ImovelZapAi\SuperAdmin\Application\Services\PlatformHealthProbe;
use ImovelZapAi\SuperAdmin\Application\Services\PlatformSettingsStore;
use ImovelZapAi\SuperAdmin\Domain\Enums\PlatformIncidentSeverity;
use ImovelZapAi\SuperAdmin\Domain\Enums\PlatformIncidentStatus;
use ImovelZapAi\SuperAdmin\Application\Actions\ManageIncidentAction;
use ImovelZapAi\SuperAdmin\Infrastructure\Persistence\Eloquent\PlatformIncidentModel;
use ImovelZapAi\Tenancy\Domain\Enums\TenantStatus;
use ImovelZapAi\Tenancy\Infrastructure\Persistence\Eloquent\TenantModel;
use Throwable;

final class PlatformApiController
{
    public function tenants(Request $request): JsonResponse
    {
        $q = trim((string) $request->query('q', ''));
        $query = TenantModel::query()->orderBy('name');
        if ($q !== '') {
            $query->where(function ($b) use ($q): void {
                $b->where('name', 'ilike', "%{$q}%")->orWhere('slug', 'ilike', "%{$q}%");
            });
        }

        return response()->json(['data' => $query->limit(100)->get()]);
    }

    public function showTenant(string $tenant): JsonResponse
    {
        return response()->json(['data' => TenantModel::query()->findOrFail($tenant)]);
    }

    public function storeTenant(Request $request, PlatformCreateTenantAction $action): JsonResponse
    {
        $data = $request->validate([
            'name' => ['required', 'string'],
            'slug' => ['required', 'string'],
            'status' => ['nullable', 'string'],
        ]);
        $status = TenantStatus::tryFrom((string) ($data['status'] ?? 'trial')) ?? TenantStatus::Trial;
        $tenant = $action->execute($data['name'], $data['slug'], $status);

        return response()->json(['data' => $tenant], 201);
    }

    public function suspendTenant(string $tenant, PlatformChangeTenantStatusAction $action): JsonResponse
    {
        return response()->json(['data' => $action->execute($tenant, TenantStatus::Suspended)]);
    }

    public function activateTenant(string $tenant, PlatformChangeTenantStatusAction $action): JsonResponse
    {
        return response()->json(['data' => $action->execute($tenant, TenantStatus::Active)]);
    }

    public function metrics(GetPlatformMetricsQuery $query, Request $request): JsonResponse
    {
        $days = max(1, min(90, (int) $request->query('days', 30)));

        return response()->json(['data' => $query->execute($days)]);
    }

    public function health(PlatformHealthProbe $probe): JsonResponse
    {
        return response()->json(['data' => $probe->probe(persist: true)]);
    }

    public function incidents(): JsonResponse
    {
        return response()->json([
            'data' => PlatformIncidentModel::query()->orderByDesc('created_at')->limit(50)->get(),
        ]);
    }

    public function storeIncident(Request $request, ManageIncidentAction $action): JsonResponse
    {
        $data = $request->validate([
            'title' => ['required', 'string'],
            'description' => ['nullable', 'string'],
            'severity' => ['nullable', 'string'],
            'affected_tenant_ids' => ['nullable', 'array'],
        ]);
        $severity = PlatformIncidentSeverity::tryFrom((string) ($data['severity'] ?? 'medium'))
            ?? PlatformIncidentSeverity::Medium;

        return response()->json([
            'data' => $action->open(
                $data['title'],
                $data['description'] ?? null,
                $severity,
                $data['affected_tenant_ids'] ?? null,
            ),
        ], 201);
    }

    public function settings(PlatformSettingsStore $store): JsonResponse
    {
        return response()->json([
            'data' => [
                'maintenance_mode' => $store->maintenanceMode(),
                'feature_flags' => $store->featureFlags(),
                'ip_allowlist' => $store->ipAllowlist(),
            ],
        ]);
    }

    public function updateSettings(Request $request, PlatformSettingsStore $store): JsonResponse
    {
        if ($request->has('maintenance_mode')) {
            $store->set('maintenance_mode', $request->boolean('maintenance_mode'));
        }
        if ($request->has('feature_flags') && is_array($request->input('feature_flags'))) {
            $store->set('feature_flags', $request->input('feature_flags'));
        }
        if ($request->has('ip_allowlist') && is_array($request->input('ip_allowlist'))) {
            $store->set('ip_allowlist', $request->input('ip_allowlist'));
        }

        return $this->settings($store);
    }
}
