<?php

namespace App\Services;

use App\Models\AwardType;
use App\Models\User;

class MalawiTerritoryAwardService
{
    public const COMPANY_SLUG = MalawiTerritoryRosterSync::COMPANY_SLUG;

    /** @var array<string, AwardType> */
    private array $awardTypes = [];

    public function seedForCompany(?User $company = null): array
    {
        $company = $company ?? $this->resolveCompany();
        $this->awardTypes = [];

        foreach (config('malawi_territory_awards.types', []) as $definition) {
            $awardType = AwardType::updateOrCreate(
                [
                    'created_by' => $company->id,
                    'name' => $definition['name'],
                ],
                [
                    'description' => $definition['description'],
                    'status' => 'active',
                ]
            );

            $this->awardTypes[$definition['name']] = $awardType;
        }

        return [
            'award_types' => count($this->awardTypes),
        ];
    }

    public function awardType(string $name, ?User $company = null): ?AwardType
    {
        if (isset($this->awardTypes[$name])) {
            return $this->awardTypes[$name];
        }

        $company ??= $this->resolveCompany();

        return AwardType::where('created_by', $company->id)
            ->where('name', $name)
            ->first();
    }

    private function resolveCompany(): User
    {
        $company = User::where('slug', self::COMPANY_SLUG)->where('type', 'company')->first();
        if (! $company) {
            throw new \RuntimeException('Malawi Territory company not found.');
        }

        return $company;
    }
}
