<?php

namespace App\Services\Reports;

use App\Models\BrandKit;
use App\Models\Client;
use App\Models\ReportTemplate;

class BrandKitResolver
{
    public function resolve(?ReportTemplate $template = null, ?Client $client = null): ?BrandKit
    {
        if ($template?->brandKit?->is_active) {
            return $template->brandKit;
        }

        if ($template?->brand_kit_id && ! $template->relationLoaded('brandKit')) {
            $brandKit = BrandKit::active()->find($template->brand_kit_id);
            if ($brandKit) {
                return $brandKit;
            }
        }

        $client = $client ?: $template?->client;
        if ($client) {
            $clientBrand = BrandKit::query()
                ->active()
                ->where('client_id', $client->id)
                ->where('is_default', true)
                ->orderBy('sort_order')
                ->first();

            if ($clientBrand) {
                return $clientBrand;
            }
        }

        return BrandKit::query()
            ->active()
            ->whereNull('client_id')
            ->where('is_default', true)
            ->orderBy('sort_order')
            ->first();
    }

    /** @return array<string, mixed> */
    public function settings(?ReportTemplate $template = null, ?Client $client = null): array
    {
        $brandKit = $this->resolve($template, $client);
        if (! $brandKit) {
            return [];
        }

        return $brandKit->toReportSettings();
    }
}
