<?php

namespace App\Console\Commands;

use App\Models\PartnerCredential;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class IssuePartnerCredential extends Command
{
    /**
     * Usage: php artisan partner:issue "Partner Name" 123456
     * user_id must be an existing service member account created for this partner
     * (its cashback ledger stays isolated from real members).
     */
    protected $signature = 'partner:issue {name : Partner display name} {user_id : Existing service user (users.user_id) owning this partner\'s clicks}';

    protected $description = 'Issue API credentials for a service partner (prints the key ONCE)';

    public function handle()
    {
        $name = $this->argument('name');
        $userId = (int) $this->argument('user_id');

        if (!DB::table('users')->where('user_id', $userId)->exists()) {
            $this->error("users.user_id {$userId} does not exist — create the service account first.");
            return 1;
        }
        if (PartnerCredential::where('name', $name)->exists()) {
            $this->error("Partner '{$name}' already has credentials. Revoke (is_active=0) and reissue under a new name if rotation is needed.");
            return 1;
        }

        $plainKey = 'yjp_' . bin2hex(random_bytes(24));

        $partner = PartnerCredential::create([
            'name' => $name,
            'api_key_hash' => hash('sha256', $plainKey),
            'user_id' => $userId,
            'is_active' => true,
        ]);

        $this->info("Partner #{$partner->id} '{$name}' created (service user {$userId}).");
        $this->warn('API key (shown ONCE, store it in the partner\'s secret manager):');
        $this->line($plainKey);

        return 0;
    }
}
