<?php

declare(strict_types=1);

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Http\Requests\User\RegisterEmployerRequest;
use App\Http\Requests\User\UpdateProfileRequest;
use App\Http\Resources\UserResource;
use App\Models\User;
use App\Services\UserService;
use App\Support\ApiResponse;
use App\Support\AvatarPath;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class AuthProfileController extends Controller
{
    public function __construct(private readonly UserService $userService) {}

    public function me(Request $request)
    {
        $user = $request->user()->load(['roles', 'producer', 'expert', 'province', 'county']);

        return ApiResponse::success(
            (new UserResource($user))->resolve()
        );
    }

    public function update(UpdateProfileRequest $request)
    {
        return $this->persistProfile($request, $request->user());
    }

    public function updateById(UpdateProfileRequest $request, User $routeUser)
    {
        if ($request->user()->id !== $routeUser->id && ! $request->user()->hasRole(User::ROLE_ADMIN)) {
            return ApiResponse::forbidden('شما مجوز ویرایش این کاربر را ندارید.');
        }

        return $this->persistProfile($request, $routeUser);
    }

    private function persistProfile(UpdateProfileRequest $request, User $user)
    {
        $data = $request->validated();

        $user->first_name = $data['first_name'];
        $user->last_name = $data['last_name'];
        $user->username = $data['name'];
        $user->cellphone = $data['cellphone'];
        $user->national_code = $data['national_code'] ?? null;
        $user->email = $data['email'] ?? null;
        $user->phone = $data['phone'] ?? null;
        $user->dob = $data['dob'] ?? null;
        $user->address = $data['address'] ?? null;

        if (array_key_exists('avatar', $data) && filled($data['avatar'])) {
            $user->avatar = AvatarPath::normalize($data['avatar']);
        }

        if (filled($data['password'] ?? null)) {
            $user->password = Hash::make($data['password']);
            $user->login_type = 1;
        }

        $user->save();
        $user->load(['roles', 'producer', 'expert', 'province', 'county']);

        return ApiResponse::success(
            (new UserResource($user))->resolve(),
            'اطلاعات کاربری با موفقیت به‌روزرسانی شد.'
        );
    }

    public function registerEmployer(RegisterEmployerRequest $request)
    {
        $payload = $request->validated();
        $payload['password'] = Hash::make($payload['password']);
        $payload['account_type'] = User::ACCOUNT_EMPLOYER;
        $payload['status'] = 1;
        $payload['is_blocked'] = false;
        $payload['login_type'] = 1;

        $user = User::create($payload);
        $user->syncRoles([User::ROLE_EMPLOYER, User::ROLE_USER]);

        return $this->userService->authSuccess($user);
    }
}
