<?php

namespace App\Actions\Staff;

use App\Contracts\StaffRepositoryContract;
use App\Models\User;
use App\Services\Audit\AuditLogService;
class UpdateStaffAction
{
    public function __construct(
        private readonly StaffRepositoryContract $staff,
        private readonly AuditLogService $auditLog,
    ) {}

    /**
     * @param  array<string, mixed>  $data
     */
    public function execute(User $user, array $data): User
    {
        $payload = collect($data)->only([
            'name', 'email', 'phone', 'status', 'department_id', 'designation_id',
        ])->filter(fn ($value) => $value !== null)->all();

        if ($user->isPrimaryAdmin()) {
            unset($payload['status']);
            $data['roles'] = [config('permissions.super_admin_role', 'Super Admin')];
        }

        if (! empty($data['password'])) {
            $payload['password'] = $data['password'];
        }

        $updated = $this->staff->update($user, $payload);

        if (array_key_exists('roles', $data)) {
            $updated->syncRoles($data['roles'] ?? []);
        }

        $this->auditLog->log('staff.updated', $updated, [
            'email' => $updated->email,
        ]);

        return $updated;
    }
}
