<?php

namespace App\Services;

use App\Models\Service;
use App\Models\ServiceVersion;

class ServiceConfigurationResolver
{
    public function resolve(Service $service, ?int $versionNumber = null): array
    {
        if ($versionNumber) {
            $version = ServiceVersion::where('service_id', $service->id)->where('version_number', $versionNumber)->first();
            if ($version && ! empty($version->configuration_json)) {
                return $version->configuration_json;
            }
        }

        // Fetch published version snapshot
        $publishedVersion = ServiceVersion::where('service_id', $service->id)->where('status', 'published')->latest()->first();

        if ($publishedVersion && ! empty($publishedVersion->configuration_json)) {
            return $publishedVersion->configuration_json;
        }

        // Fallback to active dynamic models
        return [
            'service' => $service->toArray(),
            'forms' => $service->forms ?? [],
            'document_rules' => $service->documentRules ?? [],
            'fee_components' => $service->feeComponents ?? [],
            'workflow_stages' => $service->workflowStages ?? [],
        ];
    }
}
