<?php

namespace App\Http\Controllers;

use App\Http\Requests\User\SigninUserRequest;
use App\Http\Requests\User\SignoutUserRequest;
use App\Http\Requests\User\StoreUserRequest;
use App\Http\Resources\UserResource;
use App\Models\User;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    public function signin(SigninUserRequest $request)
    {
        $credentials = $request->validated();

        $user = User::where('email', $credentials['email'])->first();

        if (! $user || ! Hash::check($credentials['password'], $user->password)) {
            return $this->error([
                'message' => 'Invalid credentials.',
                'code' => 401,
            ], 401);
        }

        $token = $user->createToken('ChristJesus '.$user->email)->plainTextToken;

        return $this->success([
            'message' => 'Login successful.',
            'data' => [
                'user' => new UserResource($user),
                'token' => $token,
            ],
        ], 200);
    }

    public function signup(StoreUserRequest $request)
    {
        $validatedData = $request->validated();
        $companyId = $request->company_id;

        $user = User::create([$validatedData, $companyId]);

        return $this->success([
            'message' => 'User created successfully.',
            'code' => 201,
            'data' => [
                'user' => new UserResource($user),
                'token' => $user->createToken('ChristJesus '.$user->user_email)->plainTextToken,
            ],
        ]);
    }

    public function signout(SignoutUserRequest $request)
    {
        $user = $request->user();

        if ($request->boolean('all_devices')) {
            $user->tokens()->delete();
        } else {
            $user->currentAccessToken()->delete();
        }

        return $this->success([
            'message' => $request->boolean('all_devices')
                ? 'Logged out from all devices.'
                : 'Logged out successfully.',
        ]);
    }
}
