<?php

namespace Database\Seeders;

use App\Models\Tenant;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class SuperAdminSeeder extends Seeder
{
    public function run(): void
    {
        $email = env('ADMIN_EMAIL', 'admin@example.com');
        $password = env('ADMIN_PASSWORD', 'ChangeMe123!');
        $user = User::updateOrCreate(['email' => $email], [
            'first_name' => 'Super',
            'last_name' => 'Admin',
            'password' => Hash::make($password),
            'role' => 'super_admin',
        ]);

        $tenantSlug = env('OWNER_TENANT_SLUG', 'owner-tenant');
        $tenantName = env('OWNER_TENANT_NAME', 'Owner Tenant');

        $tenant = Tenant::query()->firstOrCreate(
            ['slug' => $tenantSlug],
            [
                'name' => $tenantName,
                'email' => $email,
                'contact_email' => $email,
                'user_id' => $user->id,
                'is_active' => true,
                'is_suspended' => false,
                'settings' => [
                    'contact_email' => $email,
                ],
            ],
        );

        if (! $tenant->slug) {
            $tenant->forceFill(['slug' => Str::slug($tenantName)])->save();
        }

        if (! $tenant->user_id) {
            $tenant->forceFill(['user_id' => $user->id])->save();
        }

        if (! $tenant->email) {
            $tenant->forceFill(['email' => $email])->save();
        }

        if (! $tenant->contact_email) {
            $tenant->forceFill(['contact_email' => $email])->save();
        }

        if ($user->tenant_id !== $tenant->id) {
            $user->forceFill(['tenant_id' => $tenant->id])->save();
        }
    }
}
