<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\UserAccount;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;
use Illuminate\Database\QueryException;

class AuthController extends Controller
{
    public function register(Request $request)
    {
        try {

            Log::info('Register request diterima', [
                'user_id' => $request->user_id,
                'email_address' => $request->email_address
            ]);

            $request->validate([
                'user_id' => 'required|unique:user_accounts',
                'full_name' => 'required',
                'date_of_birth' => 'required|date',
                'email_address' => 'required|email|unique:user_accounts',
                'password' => 'required|min:6'
            ]);

            $user = UserAccount::create([
                'user_id' => $request->user_id,
                'full_name' => $request->full_name,
                'date_of_birth' => $request->date_of_birth,
                'email_address' => $request->email_address,
                'password' => Hash::make($request->password),
                'insert_date' => now(),
                'lock_status' => false,
                'active_status' => true
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Register berhasil'
            ]);

        } catch (ValidationException $e) {

            return response()->json([
                'success' => false,
                'message' => collect($e->errors())
                                ->flatten()
                                ->first(),
                'errors' => $e->errors()
            ], 422);
        } catch (QueryException $e) {

            Log::error('Database Error', [
                'message' => $e->getMessage(),
                'sql' => $e->getSql(),
                'bindings' => $e->getBindings()
            ]);

            return response()->json([
                'success' => false,
                'message' => 'Gagal menyimpan data ke database',
                'detail' => $e->getMessage()
            ], 500);

        } catch (\Exception $e) {

            Log::error('Register gagal', [
                'message' => $e->getMessage(),
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);

            return response()->json([
                'success' => false,
                'message' => 'Terjadi kesalahan sistem',
                'detail' => $e->getMessage()
            ], 500);
        }
    }

    public function login(Request $request)
    {
        $request->validate([
            'user_id' => 'required',
            'password' => 'required'
        ]);

        $user = UserAccount::where(
            'user_id',
            $request->user_id
        )->first();

        if (!$user) {
            return response()->json([
                'success' => false,
                'message' => 'User tidak ditemukan'
            ], 401);
        }

        if (!Hash::check(
            $request->password,
            $user->password
        )) {
            return response()->json([
                'success' => false,
                'message' => 'Password salah'
            ], 401);
        }

        if ($user->lock_status) {
            return response()->json([
                'success' => false,
                'message' => 'Account terkunci'
            ], 403);
        }

        if (!$user->active_status) {
            return response()->json([
                'success' => false,
                'message' => 'Account tidak aktif'
            ], 403);
        }

        $token = auth('api')->login($user);

        return response()->json([
            'success' => true,
            'token_type' => 'Bearer',
            'access_token' => $token,
            'expires_in' => auth('api')->factory()->getTTL() * 60,
            'user' => [
                'id' => $user->id,
                'user_id' => $user->user_id,
                'full_name' => $user->full_name,
                'email_address' => $user->email_address
            ]
        ]);
    }

    public function me()
    {
        return response()->json([
            'success' => true,
            'user' => auth('api')->user()
        ]);
    }

    
}