<?php

namespace App\Http\Resources\Tenant;

use App\Models\Event;
use App\Models\EventPhotoboothSetting;
use App\Models\PhotoboothSetting;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class PhotoboothStatusResource extends JsonResource
{
    /**
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        $payload = $this->resolvePayload();
        /** @var Event $event */
        $event = $payload['event'];
        /** @var PhotoboothSetting $settings */
        $settings = $payload['settings'];

        $event->loadMissing('photoboothSetting');
        $eventSetting = $event->photoboothSetting;

        $mode = $eventSetting?->mode ?? 'ftp';
        $isSparkbooth = $mode === 'sparkbooth';

        $password = $eventSetting?->getAttribute('plain_password') ?? $eventSetting?->password;

        $activeUsername = $eventSetting?->username;
        $activeStatus = $eventSetting?->status ?? 'inactive';
        $activeExpires = $eventSetting?->expires_at;

        $sparkMetrics = [
            'last_upload_at' => optional($eventSetting?->last_upload_at)->toIso8601String(),
            'uploads_24h' => (int) ($eventSetting?->uploads_last_24h ?? 0),
            'uploads_total' => (int) ($eventSetting?->uploads_total ?? 0),
        ];

        return [
            'mode' => $mode,
            'enabled' => (bool) ($eventSetting?->enabled),
            'status' => $activeStatus,
            'username' => $activeUsername,
            'password' => $password,
            'path' => $eventSetting?->path,
            'ftp_url' => $isSparkbooth ? null : $this->buildFtpUrl($eventSetting, $settings, $password),
            'upload_url' => $isSparkbooth ? route('api.v1.photobooth.upload') : null,
            'expires_at' => optional($activeExpires)->toIso8601String(),
            'rate_limit_per_minute' => (int) $settings->rate_limit_per_minute,
            'ftp' => [
                'host' => config('photobooth.ftp.host'),
                'port' => $settings->ftp_port,
                'require_ftps' => (bool) $settings->require_ftps,
            ],
            'metrics' => $isSparkbooth ? $sparkMetrics : null,
            'sparkbooth' => [
                'enabled' => $mode === 'sparkbooth' && (bool) ($eventSetting?->enabled),
                'status' => $mode === 'sparkbooth' ? ($eventSetting?->status) : 'inactive',
                'username' => $mode === 'sparkbooth' ? $eventSetting?->username : null,
                'password' => $mode === 'sparkbooth' ? $password : null,
                'expires_at' => $mode === 'sparkbooth' ? optional($eventSetting?->expires_at)->toIso8601String() : null,
                'upload_url' => route('api.v1.photobooth.upload'),
                'response_format' => ($eventSetting?->metadata ?? [])['sparkbooth_response_format'] ?? config('photobooth.sparkbooth.response_format', 'json'),
                'metrics' => $sparkMetrics,
            ],
        ];
    }

    /**
     * @return array{event: Event, settings: PhotoboothSetting}
     */
    protected function resolvePayload(): array
    {
        $resource = $this->resource;

        if ($resource instanceof Event) {
            return [
                'event' => $resource,
                'settings' => PhotoboothSetting::current(),
            ];
        }

        return [
            'event' => $resource['event'] ?? $resource,
            'settings' => $resource['settings'] ?? PhotoboothSetting::current(),
        ];
    }

    protected function buildFtpUrl(?EventPhotoboothSetting $eventSetting, PhotoboothSetting $settings, ?string $password): ?string
    {
        $host = config('photobooth.ftp.host');
        $username = $eventSetting?->username;

        if (! $host || ! $username || ! $password) {
            return null;
        }

        $scheme = $settings->require_ftps ? 'ftps' : 'ftp';
        $port = $settings->ftp_port ?: config('photobooth.ftp.port', 21);

        return sprintf('%s://%s:%s@%s:%d', $scheme, $username, $password, $host, $port);
    }
}
