<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\User;
use App\Models\Customer;
use App\Models\Role;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;

class CreateTestCustomer extends Command
{
    protected $signature = 'create:test-customer';
    protected $description = 'Create a test customer with known credentials';

    public function handle()
    {
        $email = 'test@example.com';
        $password = 'password123';

        DB::transaction(function () use ($email, $password) {
            // Delete existing test customer and user
            Customer::where('email', $email)->delete();
            User::where('email', $email)->delete();

            // Create user
            $user = User::create([
                'name' => 'Test Customer',
                'email' => $email,
                'password' => Hash::make($password),
                'phone' => '555-0123',
                'status' => 'active',
            ]);

            // Assign customer_portal role
            $customerRole = Role::where('name', 'customer_portal')->first();
            if ($customerRole) {
                $user->roles()->attach($customerRole->id, [
                    'is_active' => true,
                    'assigned_at' => now(),
                ]);
            }

            // Create customer
            $customer = Customer::create([
                'user_id' => $user->id,
                'first_name' => 'Test',
                'last_name' => 'Customer',
                'email' => $email,
                'phone' => '555-0123',
                'address' => '123 Test St',
                'city' => 'Test City',
                'state' => 'CA',
                'zip_code' => '12345',
                'status' => 'active',
            ]);

            $this->info("Test customer created successfully!");
            $this->info("Email: {$email}");
            $this->info("Password: {$password}");
            $this->info("User ID: {$user->id}");
            $this->info("Customer ID: {$customer->id}");
        });

        return 0;
    }
}
