<?php

namespace Maestro\Core\Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use Maestro\Core\Models\Organization;
use Maestro\Core\Support\AuthUserResolver;
use Maestro\Core\Support\PermissionGuardName;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

class UserSeeder extends Seeder
{
    public function run(): void
    {
        $userClass = AuthUserResolver::eloquentModelClass();

        $guardName = PermissionGuardName::forApp();

        $permissionNames = [
            'platform.superadmin',
            'activitylog.view',
            'settings.organization.view',
            'settings.organization.edit',
            'users.view',
            'users.create',
            'users.edit',
            'users.delete',
            'users.assign-roles',
            'roles.view',
            'roles.create',
            'roles.edit',
            'roles.delete',
        ];

        foreach ($permissionNames as $name) {
            Permission::firstOrCreate([
                'name' => $name,
                'guard_name' => $guardName,
            ]);
        }

        $adminRole = Role::firstOrCreate([
            'name' => 'admin',
            'guard_name' => $guardName,
        ]);

        $adminRole->givePermissionTo(
            Permission::query()
                ->where('guard_name', $guardName)
                ->whereIn('name', $permissionNames)
                ->get(),
        );

        $organization = Organization::query()->updateOrCreate(
            ['id' => 1],
            [
                'name' => 'Maestro Demo BV',
                'company_name' => 'Maestro Demo BV',
                'street' => 'Stationsplein 1',
                'address_line_1' => 'Stationsplein 1',
                'city' => 'Amsterdam',
                'postal_code' => '1012 AB',
                'country_code' => 'nl',
                'country' => 'Nederland',
            ],
        );

        $user = $userClass::query()->updateOrCreate(
            ['email' => 'demo@example.com'],
            [
                'name' => 'Demo Admin',
                'password' => Hash::make('password'),
                'organization_id' => $organization->id,
                'email_verified_at' => now(),
                'is_active' => true,
            ],
        );

        $user->syncRoles(['admin']);
    }
}
