<?php

namespace App\Console\Commands;

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

class SeedIndicatorCategoriesCommand extends Command
{
    protected $signature = 'hrm:seed-indicator-categories
                            {--company= : Company user ID or email}
                            {--force : Add missing categories even if some already exist}';

    protected $description = 'Seed default performance indicator categories for a company';

    public function handle(PerformanceIndicatorCategorySetupService $service): int
    {
        $onlyEmpty = ! $this->option('force');

        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, $onlyEmpty);
                $this->line(($result['company_name'] ?? $company->name) . ': created ' . $result['categories'] . ' categories, ' . $result['indicators'] . ' indicators.');
            } else {
                $result = $service->seedForMalawiTerritory($onlyEmpty);
                $this->info('Company: ' . ($result['company_email'] ?? ''));
                $this->info('Categories created: ' . $result['categories']);
                $this->info('Indicators created: ' . $result['indicators']);
                if (($result['skipped_categories'] ?? 0) > 0) {
                    $this->line('Skipped (already exist): ' . $result['skipped_categories']);
                }
            }
        } catch (\Throwable $e) {
            $this->error($e->getMessage());

            return self::FAILURE;
        }

        return self::SUCCESS;
    }
}
