<?php

namespace App\Console\Commands;

use App\Services\SupabaseService;
use Illuminate\Console\Command;

/**
 * Membuat akun instansi (auth.users + public.users + public.instansi) via CLI.
 *
 * Berguna untuk bootstrap akun admin pertama, karena menu buat-akun di web
 * dijaga middleware 'admin'.
 *
 * Contoh:
 *   php artisan mantao:create-instansi "admin@bps.go.id" "BPS Kota Parepare (Admin)" --level=admin
 *   php artisan mantao:create-instansi "opd@parepare.go.id" "Dinas Kesehatan"
 */
class CreateInstansiUser extends Command
{
    protected $signature = 'mantao:create-instansi
        {email : Email akun}
        {nama_instansi : Nama instansi}
        {--password= : Password (default: BpsMantao2025!)}
        {--level=user : Peran mantao: admin | user}';

    protected $description = 'Buat akun instansi baru di Supabase (auth + users + instansi)';

    public function handle(SupabaseService $supabase): int
    {
        if (!$supabase->isConfigured()) {
            $this->error('Konfigurasi Supabase belum lengkap. Periksa SUPABASE_* di .env.');
            return self::FAILURE;
        }

        $email = $this->argument('email');
        $namaInstansi = $this->argument('nama_instansi');
        $password = $this->option('password') ?: 'BpsMantao2025!';
        $level = $this->option('level');

        if (!in_array($level, ['admin', 'user'], true)) {
            $this->error("Nilai --level harus 'admin' atau 'user'.");
            return self::FAILURE;
        }

        if ($supabase->emailExists($email)) {
            $this->error("Email {$email} sudah terdaftar di tabel users.");
            return self::FAILURE;
        }

        try {
            $this->line('Membuat akun Supabase Auth...');
            $authUid = $supabase->adminCreateUser($email, $password, ['full_name' => $namaInstansi]);

            $this->line('Melengkapi baris public.users...');
            $userId = $supabase->ensureUserRow($authUid, $email, [
                'name' => $namaInstansi,
                'role' => 'instansi',
            ]);

            $this->line('Insert ke public.instansi...');
            $supabase->insertInstansi([
                'user_id' => $userId,
                'nama_instansi' => $namaInstansi,
                'level' => $level,
            ]);
        } catch (\Throwable $e) {
            $this->error('Gagal: ' . $e->getMessage());
            return self::FAILURE;
        }

        $this->info("Akun instansi berhasil dibuat.");
        $this->table(
            ['auth_uid', 'user_id', 'email', 'nama_instansi', 'level'],
            [[$authUid, $userId, $email, $namaInstansi, $level]]
        );
        $this->line("Password: {$password}");

        return self::SUCCESS;
    }
}
