<?php

declare(strict_types=1);

namespace App\Services\Provisioning;

use App\Models\ProvisioningLog;
use App\Models\Service;
use App\Notifications\ServiceCredentialsNotification;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Laravel\Cashier\Subscription;
use RuntimeException;

class SynergyCPService implements ProvisioningServiceInterface
{
    private readonly string $baseUrl;

    private readonly string $token;

    public function __construct()
    {
        // Read from database settings (configured via admin panel)
        $this->baseUrl = rtrim(\App\Models\Setting::get('synergycp_api_url', ''), '/');
        $this->token = \App\Models\Setting::get('synergycp_api_token', '');
    }

    public function provision(Subscription $subscription): Service
    {
        $plan = $subscription->plan;
        $user = $subscription->user;

        if (! $plan) {
            throw new RuntimeException('Subscription has no associated plan.');
        }

        $service = Service::firstOrCreate(
            ['subscription_id' => $subscription->id, 'service_type' => 'dedicated'],
            [
                'user_id' => $user->id,
                'plan_id' => $plan->id,
                'platform' => 'synergycp',
                'status' => 'pending',
            ],
        );

        if ($service->status === 'failed') {
            $service->update(['status' => 'pending']);
        }

        $this->logAction($service, 'provision', 'pending');

        try {
            $response = $this->client()->post('/api/v1/servers', [
                'plan_id' => $plan->features['synergycp_plan_id'] ?? null,
                'client_email' => $user->email,
                'hostname' => $plan->features['default_hostname'] ?? 'dedicated.ezscale.cloud',
            ]);

            if (! $response->successful()) {
                $this->logAction($service, 'provision', 'failed', $response->json(), $response->body());

                throw new RuntimeException("SynergyCP provisioning failed: {$response->body()}");
            }

            $data = $response->json();
            $serverId = (string) ($data['data']['id'] ?? $data['id'] ?? '');

            $service->update([
                'platform_service_id' => $serverId,
                'status' => 'active',
                'ipv4_address' => $data['data']['ip_address'] ?? $data['ip_address'] ?? null,
                'hostname' => $data['data']['hostname'] ?? $data['hostname'] ?? null,
                'provisioned_at' => now(),
            ]);

            $this->logAction($service, 'provision', 'success', $data);

            $service = $service->fresh();

            if ($service->user) {
                $service->user->notify(new ServiceCredentialsNotification($service, [
                    'username' => $data['data']['username'] ?? 'root',
                    'password' => $data['data']['password'] ?? 'see control panel',
                    'hostname' => $service->hostname ?? $service->ipv4_address ?? 'N/A',
                    'ip_address' => $service->ipv4_address ?? 'Pending',
                    'port' => $data['data']['ssh_port'] ?? 22,
                    'panel_url' => $data['data']['ipmi_url'] ?? null,
                ]));
            }

            return $service;
        } catch (RuntimeException $e) {
            throw $e;
        } catch (\Exception $e) {
            $this->logAction($service, 'provision', 'failed', errorMessage: $e->getMessage());

            $service->update(['status' => 'failed']);

            throw new RuntimeException("SynergyCP provisioning error: {$e->getMessage()}", 0, $e);
        }
    }

    public function suspend(Service $service): bool
    {
        $this->validateServicePlatform($service);

        $this->logAction($service, 'suspend', 'pending');

        try {
            $response = $this->client()->post("/api/v1/servers/{$service->platform_service_id}/suspend");

            if (! $response->successful()) {
                $this->logAction($service, 'suspend', 'failed', $response->json(), $response->body());

                return false;
            }

            $service->update([
                'status' => 'suspended',
                'suspended_at' => now(),
            ]);

            $this->logAction($service, 'suspend', 'success', $response->json());

            return true;
        } catch (\Exception $e) {
            Log::error('SynergyCP suspend failed', [
                'service_id' => $service->id,
                'error' => $e->getMessage(),
            ]);

            $this->logAction($service, 'suspend', 'failed', errorMessage: $e->getMessage());

            return false;
        }
    }

    public function unsuspend(Service $service): bool
    {
        $this->validateServicePlatform($service);

        $this->logAction($service, 'unsuspend', 'pending');

        try {
            $response = $this->client()->post("/api/v1/servers/{$service->platform_service_id}/unsuspend");

            if (! $response->successful()) {
                $this->logAction($service, 'unsuspend', 'failed', $response->json(), $response->body());

                return false;
            }

            $service->update([
                'status' => 'active',
                'suspended_at' => null,
            ]);

            $this->logAction($service, 'unsuspend', 'success', $response->json());

            return true;
        } catch (\Exception $e) {
            Log::error('SynergyCP unsuspend failed', [
                'service_id' => $service->id,
                'error' => $e->getMessage(),
            ]);

            $this->logAction($service, 'unsuspend', 'failed', errorMessage: $e->getMessage());

            return false;
        }
    }

    public function terminate(Service $service): bool
    {
        $this->validateServicePlatform($service);

        $this->logAction($service, 'terminate', 'pending');

        try {
            $response = $this->client()->delete("/api/v1/servers/{$service->platform_service_id}");

            if (! $response->successful()) {
                $this->logAction($service, 'terminate', 'failed', $response->json(), $response->body());

                return false;
            }

            $service->update([
                'status' => 'terminated',
                'terminated_at' => now(),
            ]);

            $this->logAction($service, 'terminate', 'success', $response->json());

            return true;
        } catch (\Exception $e) {
            Log::error('SynergyCP terminate failed', [
                'service_id' => $service->id,
                'error' => $e->getMessage(),
            ]);

            $this->logAction($service, 'terminate', 'failed', errorMessage: $e->getMessage());

            return false;
        }
    }

    /**
     * @return array{status: string, ip_address?: string, hostname?: string, platform_data?: array<string, mixed>}
     */
    public function getStatus(Service $service): array
    {
        $this->validateServicePlatform($service);

        try {
            $response = $this->client()->get("/api/v1/servers/{$service->platform_service_id}");

            if (! $response->successful()) {
                return ['status' => 'unknown'];
            }

            $data = $response->json();
            $serverData = $data['data'] ?? $data;

            return [
                'status' => $serverData['status'] ?? 'unknown',
                'ip_address' => $serverData['ip_address'] ?? $service->ipv4_address,
                'hostname' => $serverData['hostname'] ?? $service->hostname,
                'platform_data' => $serverData,
            ];
        } catch (\Exception $e) {
            Log::error('SynergyCP getStatus failed', [
                'service_id' => $service->id,
                'error' => $e->getMessage(),
            ]);

            return ['status' => 'unknown'];
        }
    }

    /**
     * @return array{username?: string, password?: string, url?: string, additional?: array<string, mixed>}
     */
    public function getCredentials(Service $service): array
    {
        $this->validateServicePlatform($service);

        $stored = $service->credentials ?? [];

        try {
            $response = $this->client()->get("/api/v1/servers/{$service->platform_service_id}");

            if ($response->successful()) {
                $data = $response->json();
                $serverData = $data['data'] ?? $data;

                return [
                    'username' => $stored['username'] ?? 'root',
                    'password' => $stored['password'] ?? null,
                    'url' => $serverData['ipmi_url'] ?? null,
                    'additional' => [
                        'ip_address' => $serverData['ip_address'] ?? $service->ipv4_address,
                        'hostname' => $serverData['hostname'] ?? $service->hostname,
                        'ipmi_ip' => $serverData['ipmi_ip'] ?? null,
                    ],
                ];
            }
        } catch (\Exception $e) {
            Log::error('SynergyCP getCredentials failed', [
                'service_id' => $service->id,
                'error' => $e->getMessage(),
            ]);
        }

        return [
            'username' => $stored['username'] ?? 'root',
            'password' => $stored['password'] ?? null,
        ];
    }

    private function client(): PendingRequest
    {
        return Http::withToken($this->token)
            ->baseUrl($this->baseUrl)
            ->acceptJson()
            ->timeout(30);
    }

    private function validateServicePlatform(Service $service): void
    {
        if (! $service->platform_service_id) {
            throw new RuntimeException('Service has no platform service ID.');
        }
    }

    /**
     * @param  array<string, mixed>|null  $response
     */
    private function logAction(
        Service $service,
        string $action,
        string $status,
        ?array $response = null,
        ?string $errorMessage = null,
    ): void {
        ProvisioningLog::create([
            'service_id' => $service->id,
            'user_id' => $service->user_id,
            'action' => $action,
            'platform' => 'synergycp',
            'platform_response' => $response,
            'status' => $status,
            'error_message' => $errorMessage,
        ]);
    }
}
