<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    public function login(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required'
        ]);

        $user = User::query()
                ->where('email', $request->email)
                ->first();

        if (!$user) {
            return response(['message' => 'User Tidak Ditemukan'], 404);
        }

        if (!Hash::check($request->password, $user->password)) {
            return response(['message' => 'Password Salah'], 403);
        }

        return response([
            'message' => 'Selamat Datang',
            'user' => $user,
            'token' => $user->createToken('app')->plainTextToken
        ]);
    }

    public function logout(Request $request)
    {
        $token = $request->bearerToken();
        Auth::user()->tokens()->where('id', $token)->delete();

        return response(['message' => 'Berhasil Logout.']);
    }
}
