<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

/**
 * Thin wrapper over Coolify v4 REST API. Used to add tenant subdomains
 * to the AutoCRM application's FQDN list when a new Company is created.
 *
 * Configure via env:
 *   COOLIFY_API_URL=http://65.21.20.141:8000
 *   COOLIFY_API_TOKEN=<token>
 *   COOLIFY_APP_UUID=<autocrm-app-uuid>
 */
class CoolifyClient
{
    public function __construct(
        protected ?string $base = null,
        protected ?string $token = null,
    ) {
        // Use config() not env() — env() returns null when config is cached
        // in production. Octane workers also cache env at boot.
        $this->base = rtrim($base ?? (string) config('services.coolify.url'), '/');
        $this->token = $token ?? (string) config('services.coolify.token');
    }

    public function isConfigured(): bool
    {
        return $this->base !== '' && $this->token !== '';
    }

    protected function http()
    {
        return Http::withToken($this->token)
            ->withHeaders(['Accept' => 'application/json'])
            ->withOptions(['verify' => false])
            ->timeout(15);
    }

    public function getApp(string $uuid): ?array
    {
        if (! $this->isConfigured()) return null;
        $r = $this->http()->get($this->base . '/api/v1/applications/' . $uuid);
        return $r->ok() ? $r->json() : null;
    }

    /**
     * Add a new domain to the application's FQDN list (idempotent).
     * Returns true if successful or already present.
     */
    public function addDomain(string $appUuid, string $url): bool
    {
        if (! $this->isConfigured()) {
            Log::warning('CoolifyClient not configured; skipping addDomain', ['url' => $url]);
            return false;
        }

        $app = $this->getApp($appUuid);
        if (! $app) {
            Log::error('CoolifyClient: cannot fetch app', ['uuid' => $appUuid]);
            return false;
        }

        $current = (string) ($app['fqdn'] ?? '');
        $domains = array_filter(array_map('trim', explode(',', $current)));
        if (in_array($url, $domains, true)) {
            return true;
        }
        $domains[] = $url;
        $newFqdn = implode(',', $domains);

        $r = $this->http()->patch(
            $this->base . '/api/v1/applications/' . $appUuid,
            ['domains' => $newFqdn]
        );

        if (! $r->successful()) {
            Log::error('CoolifyClient addDomain failed', [
                'status' => $r->status(),
                'body' => $r->body(),
            ]);
            return false;
        }

        return true;
    }

    /**
     * Trigger a redeploy on the app (after FQDN change Coolify needs redeploy
     * to update Traefik labels).
     */
    public function deploy(string $appUuid, bool $force = true): bool
    {
        if (! $this->isConfigured()) return false;
        $r = $this->http()->post($this->base . '/api/v1/deploy', [
            'uuid' => $appUuid,
            'force' => $force,
        ]);
        if (! $r->successful()) {
            // try query string variant (Coolify's GET /deploy?uuid=...)
            $r = $this->http()->post($this->base . '/api/v1/deploy?uuid=' . $appUuid . '&force=' . ($force ? 'true' : 'false'));
        }
        return $r->successful();
    }
}
