<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\User;
use App\Models\Customer;

class LinkCustomersToUsers extends Command
{
    protected $signature = 'migrate:link-customers-users';
    protected $description = 'Link existing customers to their user accounts based on email';

    public function handle()
    {
        $this->info('Linking existing customers to user accounts...');

        $customers = Customer::whereNull('user_id')->get();
        $linked = 0;
        $created = 0;

        foreach ($customers as $customer) {
            // Find matching user by email
            $user = User::where('email', $customer->email)->first();
            
            if ($user) {
                // Link existing user to customer
                $customer->update(['user_id' => $user->id]);
                $this->info("Linked customer {$customer->email} to existing user account");
                $linked++;
            } else {
                $this->warn("No user account found for customer {$customer->email}");
            }
        }

        $this->info("Migration completed:");
        $this->info("- Linked {$linked} customers to existing user accounts");
        
        return 0;
    }
}
