<?php

namespace App\Filament\Admin\Resources\Users\Pages;

use App\Filament\Admin\Resources\Users\UserResource;
use App\Models\Association;
use Filament\Facades\Filament;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Support\Facades\Log;

class CreateUser extends CreateRecord
{
    protected static string $resource = UserResource::class;

    protected function handleRecordCreation(array $data): \Illuminate\Database\Eloquent\Model
    {
        $associationId = $data['association_id'] ?? null;
        $roles = $data['roles'] ?? [];
        unset($data['association_id'], $data['roles']);

        $user = static::getModel()::create($data);

        $tenant = Filament::getTenant();
        if ($tenant) {
            // Handle association assignment if provided
            if ($associationId) {
                $association = Association::find($associationId);
                if ($association && $association->org_id === $tenant->id) {
                    $user->setAssociationInOrg($tenant, $association);
                }
            }

            Log::info('Roles are: '.implode(',', $roles));

            $user->syncRoles($roles);
        }

        return $user;
    }
}
