<?php

namespace Modules\MedOrganization\Console;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Modules\MedOrganization\Database\Seeders\OrgRolesSeeder;

/**
 * Seeds the predefined medical roles (+ the example ABAC rules) for one
 * business or for every business (spec §4 predefined_roles; audit §2).
 */
class SeedRolesCommand extends Command
{
    protected $signature = 'medorg:seed-roles {business_id? : Seed a single business (omit for all)}';

    protected $description = 'Seed the predefined medical roles and example ABAC rules per business';

    public function handle(): int
    {
        $businessId = $this->argument('business_id');

        $businessIds = $businessId !== null
            ? [(int) $businessId]
            : DB::table('business')->pluck('id')->all();

        if (empty($businessIds)) {
            $this->warn('No businesses found.');

            return self::SUCCESS;
        }

        $seeder = new OrgRolesSeeder();

        foreach ($businessIds as $id) {
            if (! DB::table('business')->where('id', $id)->exists()) {
                $this->error("Business #{$id} not found — skipped.");
                continue;
            }
            $created = $seeder->seedForBusiness((int) $id);
            $this->info("Business #{$id}: roles ensured (" . implode(', ', $created) . ').');
        }

        return self::SUCCESS;
    }
}
