<?php

namespace App\Services;

use App\Models\Tenant;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Config;

use App\Models\User;
use Illuminate\Support\Facades\Hash;

class TenantService
{
    /**
     * Create a new tenant and their database.
     */
    public function createTenant(array $data, array $userData = []): Tenant
    {
        // 1. Create Tenant Record in Central DB
        $tenant = Tenant::create($data);

        // 2. Create Tenant Database
        $this->createDatabase($tenant->database_name);

        // 3. Create Default Tenant Users (Manager, Staff, User)
        $this->createDefaultUsers($tenant, $userData);

        return $tenant;
    }

    /**
     * Create default users for the tenant
     */
    protected function createDefaultUsers(Tenant $tenant, array $userData = []): void
    {
        $defaultPassword = 'password';
        $managerPassword = $userData['password'] ?? \Illuminate\Support\Str::random(12);

        // 1. Manager
        $manager = User::create([
            'name' => $userData['name'] ?? 'Tenant Manager',
            'email' => $userData['email'] ?? 'admin@' . $tenant->domain,
            'phone_number' => $userData['phone_number'] ?? null,
            'password' => Hash::make($managerPassword),
            'tenant_id' => $tenant->id,
            'status' => 'active',
        ]);
        $manager->assignRole('Manager');

        // Store manager password temporarily if we need to return it
        $tenant->manager_password = $managerPassword;

        // 2. Staff
        $staff = User::create([
            'name' => 'Staff - ' . $tenant->name,
            'email' => 'staff@' . $tenant->domain,
            'password' => Hash::make($defaultPassword),
            'tenant_id' => $tenant->id,
            'status' => 'active',
        ]);
        $staff->assignRole('Staff');

        // 3. User
        $user = User::create([
            'name' => 'User - ' . $tenant->name,
            'email' => 'user@' . $tenant->domain,
            'password' => Hash::make($defaultPassword),
            'tenant_id' => $tenant->id,
            'status' => 'active',
        ]);
        $user->assignRole('User');
    }

    /**
     * Create the database for the tenant.
     */
    protected function createDatabase(string $databaseName): void
    {
        // Use central connection to create new DB
        DB::connection('mysql')->statement("CREATE DATABASE `{$databaseName}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");

        // Migrate Tenant DB
        // Switch to the new tenant database context temporarily for migration
        Config::set('database.connections.tenant.database', $databaseName);
        DB::purge('tenant');
        
        \Illuminate\Support\Facades\Artisan::call('migrate', [
            '--database' => 'tenant',
            '--path' => 'database/migrations/tenant',
            '--force' => true,
        ]);

        // Seed Demo Data
        try {
             \Illuminate\Support\Facades\Artisan::call('db:seed', [
                '--class' => 'Database\\Seeders\\Tenant\\TenantDemoDataSeeder',
                '--database' => 'tenant',
                '--force' => true,
            ]);
        } catch (\Exception $e) {
            // Log error but don't fail tenant creation
            \Illuminate\Support\Facades\Log::error('Initial Tenant Seeding Failed: ' . $e->getMessage());
        }
    }

    /**
     * Switch context to the given tenant.
     */
    public function switchToTenant(Tenant $tenant): void
    {
        DB::purge('tenant');
        Config::set('database.connections.tenant.database', $tenant->database_name);
        DB::reconnect('tenant');
        
        // Optionally set as default if needed, but explicit usage is safer for mixed queries
        // DB::setDefaultConnection('tenant'); 
    }
}
