<?php

namespace App\Console\Commands;

use App\Models\User;
use App\Services\GoalTypeSetupService;
use Illuminate\Console\Command;

class SeedGoalTypesCommand extends Command
{
    protected $signature = 'hrm:seed-goal-types {--company= : Company user ID or email}';

    protected $description = 'Seed default performance goal types for Malawi Territory';

    public function handle(GoalTypeSetupService $service): int
    {
        try {
            if ($companyRef = $this->option('company')) {
                $company = is_numeric($companyRef)
                    ? User::where('type', 'company')->find($companyRef)
                    : User::where('type', 'company')->where('email', $companyRef)->first();

                if (! $company) {
                    $this->error('Company not found.');

                    return self::FAILURE;
                }

                $result = $service->seedForCompany($company);
            } else {
                $result = $service->seedForMalawiTerritory();
                $this->info('Company: ' . ($result['company_email'] ?? ''));
            }

            $this->info('Goal types created: ' . $result['goal_types']);
            if (($result['skipped'] ?? 0) > 0) {
                $this->line('Skipped (already exist): ' . $result['skipped']);
            }
        } catch (\Throwable $e) {
            $this->error($e->getMessage());

            return self::FAILURE;
        }

        return self::SUCCESS;
    }
}
