<?php

namespace App\Services;

use App\Models\GoalType;
use App\Models\User;

class GoalTypeSetupService
{
    /**
     * @return array{goal_types: int, skipped: int}
     */
    public function seedForCompany(User $company): array
    {
        $definitions = config('malawi_territory_performance.goal_types', []);
        $created = 0;
        $skipped = 0;

        foreach ($definitions as $definition) {
            $exists = GoalType::query()
                ->where('created_by', $company->id)
                ->where('name', $definition['name'])
                ->exists();

            if ($exists) {
                $skipped++;

                continue;
            }

            GoalType::create([
                'name' => $definition['name'],
                'description' => $definition['description'] ?? $definition['name'],
                'status' => 'active',
                'created_by' => $company->id,
            ]);

            $created++;
        }

        return ['goal_types' => $created, 'skipped' => $skipped];
    }

    public function seedForMalawiTerritory(): array
    {
        $company = User::where('type', 'company')
            ->where('slug', MalawiTerritoryRosterSync::COMPANY_SLUG)
            ->first();

        if (! $company) {
            throw new \RuntimeException('Malawi Territory company not found.');
        }

        return array_merge(
            $this->seedForCompany($company),
            ['company_name' => $company->name, 'company_email' => $company->email]
        );
    }
}
