<?php

namespace App\Console\Commands;

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

class SeedMeetingTypesCommand extends Command
{
    protected $signature = 'hrm:seed-meeting-types
                            {--company= : Company user ID or email}
                            {--preset= : Preset key (standard, malawi_territory)}
                            {--force : Seed even if meeting types already exist}';

    protected $description = 'Seed default meeting types for one or all companies';

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

        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, $preset);
            $this->info("Created {$result['created']} meeting type(s), skipped {$result['skipped']}.");

            return self::SUCCESS;
        }

        $results = $service->seedForAllCompanies($preset, $onlyEmpty);

        foreach ($results as $row) {
            if (isset($row['message'])) {
                $this->line("{$row['company_name']}: {$row['message']}");

                continue;
            }

            $this->line("{$row['company_name']}: created {$row['created']}, skipped {$row['skipped']}");
        }

        $this->info('Meeting type seeding complete.');

        return self::SUCCESS;
    }
}
