<?php

namespace App\Services;

use App\Models\ActivityLog;
use App\Models\User;
use App\Repositories\StaffRepository;
use Illuminate\Support\Facades\Hash;

class StaffService
{
    public function __construct(protected StaffRepository $repository) {}

    public function create(array $data): User
    {
        $roles = $data['roles'] ?? [];
        unset($data['roles']);

        $data['password'] = Hash::make($data['password']);

        $user = $this->repository->create($data);
        $user->syncRoles($roles);

        ActivityLog::create([
            'user_id' => auth()->id(),
            'action' => 'staff_created',
            'resource_type' => User::class,
            'resource_id' => $user->id,
            'description' => 'Staff created: '.$user->name,
        ]);

        return $user;
    }

    public function update(User $user, array $data): bool
    {
        $roles = $data['roles'] ?? [];
        unset($data['roles']);

        if (! empty($data['password'])) {
            $data['password'] = Hash::make($data['password']);
        } else {
            unset($data['password']);
        }

        $result = $this->repository->update($user, $data);
        $user->syncRoles($roles);

        ActivityLog::create([
            'user_id' => auth()->id(),
            'action' => 'staff_updated',
            'resource_type' => User::class,
            'resource_id' => $user->id,
            'description' => 'Staff updated: '.$user->name,
        ]);

        return $result;
    }

    public function delete(User $user): bool
    {
        $result = $this->repository->delete($user);

        ActivityLog::create([
            'user_id' => auth()->id(),
            'action' => 'staff_deleted',
            'resource_type' => User::class,
            'resource_id' => $user->id,
            'description' => 'Staff deleted: '.$user->name,
        ]);

        return $result;
    }
}
