<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\DB;

use App\Models\User;
use App\Models\Message;
use App\Models\Comment;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

Route::post('/login', function (Request $request) {
    $request->validate([
        'email' => 'required|email',
        'password' => 'required',
    ]);

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

    if (!$user || !Hash::check($request->password, $user->password)) {
        throw ValidationException::withMessages([
            'email' => ['The provided credentials are incorrect.'],
        ]);
    }

    return [
        'token' => $user->createToken('login')->plainTextToken,
        'userData' => json_encode($user),
    ];
});

Route::middleware('auth:sanctum')->post('/logout', function (Request $request) {
    $user = $request->user();
    $user->tokens()->delete();
    return $user;
});

Route::middleware('auth:sanctum')->post('/get_dataset', function (Request $request) {
    $request->validate([
        'sql' => 'required',
    ]);

    $dataset = DB::select($request->sql);
    return $dataset;
});

Route::middleware('auth:sanctum')->post('/post_comment', function (Request $request) {
    $request->validate([
        'comment' => 'required',
        'blogId' => 'required',
    ]);

    Comment::insert([
        'writer' => $request->user()->id,
        'comment' => $request->comment,
        'blogId' => $request->blogId,
        'created_at' => now(),
        'updated_at' => now(),
    ]);

    return 'success';
});

Route::middleware('auth:sanctum')->post('/delete_comment', function (Request $request) {
    $request->validate([
        'commentID' => 'required',
    ]);

    Comment::where('id', '=', $request->commentID)->delete();

    return 'success';
});