<?php

namespace App\Services;

use App\Models\Branch;
use App\Models\Tenant;
use App\Models\User;
use App\Support\ModuleRegistry;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class TenantService
{
    /**
     * Register a brand-new business:
     *  1. Create the tenant record with modules auto-assigned from business_type
     *  2. Create the owner user (super-admin within the tenant)
     *  3. Link tenant → owner
     *  4. Create the first (main) branch for the tenant
     *
     * Returns ['tenant' => Tenant, 'user' => User, 'token' => string]
     */
    public function registerBusiness(array $data): array
    {
        $businessType = $data['business_type'];
        $modules      = ModuleRegistry::getModulesForType($businessType);
        $slug         = $this->generateSlug($data['business_name']);

        // ── 1. Create tenant (no owner yet) ──────────────────────────────────
        $tenant = Tenant::create([
            'name'              => $data['business_name'],
            'slug'              => $slug,
            'business_type'     => $businessType,
            'owner_id'          => null,
            'enabled_modules'   => $modules,
            'subscription_plan' => 'free',
            'is_active'         => true,
            'settings'          => [
                'currency'     => $data['currency'] ?? 'MYR',
                'timezone'     => $data['timezone'] ?? 'Asia/Kuala_Lumpur',
                'tax_rate'     => $data['tax_rate'] ?? 0,
                'tax_type'     => $data['tax_type'] ?? 'exclusive',
            ],
        ]);

        // ── 2. Create owner user ──────────────────────────────────────────────
        $user = User::create([
            'tenant_id' => $tenant->id,
            'name'      => $data['owner_name'],
            'email'     => $data['email'],
            'password'  => Hash::make($data['password']),
            'branch_id' => null,
        ]);

        $user->assignRole('super-admin');

        // ── 3. Link owner back to tenant ──────────────────────────────────────
        $tenant->update(['owner_id' => $user->id]);

        // ── 4. Create the first branch ────────────────────────────────────────
        $branch = Branch::create([
            'tenant_id' => $tenant->id,
            'name'      => $data['branch_name'] ?? $data['business_name'],
            'code'      => strtoupper(Str::limit(Str::slug($data['business_name'], ''), 6, '')),
            'address'   => $data['address'] ?? null,
            'phone'     => $data['phone'] ?? null,
            'email'     => $data['email'],
            'is_active' => true,
            'settings'  => ['stock_restriction_enabled' => true],
        ]);

        // Assign user to the first branch
        $user->update(['branch_id' => $branch->id]);

        $token = $user->createToken('auth-token')->plainTextToken;
        $user->load(['roles', 'permissions', 'branch', 'tenant']);

        return [
            'tenant' => $tenant,
            'user'   => $user,
            'token'  => $token,
        ];
    }

    /**
     * Get a tenant with its modules and settings.
     */
    public function getTenant(int $tenantId): Tenant
    {
        return Tenant::with('owner', 'branches')->findOrFail($tenantId);
    }

    /**
     * Update tenant settings (currency, timezone, tax, etc.)
     */
    public function updateSettings(Tenant $tenant, array $settings): Tenant
    {
        $current = $tenant->settings ?? [];
        $tenant->update(['settings' => array_merge($current, $settings)]);
        return $tenant->fresh();
    }

    /**
     * Toggle a module on or off for a tenant.
     */
    public function toggleModule(Tenant $tenant, string $module, bool $enable): Tenant
    {
        if ($enable) {
            $tenant->enableModule($module);
        } else {
            $tenant->disableModule($module);
        }
        return $tenant->fresh();
    }

    // ── Private helpers ──────────────────────────────────────────────────────

    private function generateSlug(string $businessName): string
    {
        $base = Str::slug($businessName);
        $slug = $base;
        $i    = 1;

        while (Tenant::where('slug', $slug)->exists()) {
            $slug = $base . '-' . $i++;
        }

        return $slug;
    }
}
