<?php

namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;

use App\Models\User;
use App\Models\Profile;
use App\Models\Turn;

class AuthController extends Controller
{
    public function authenticate(Request $request): JsonResponse
    {
        $profile = Profile::with('user')->where('id_card', $request->user)->first();
        if (!$profile) {
            return response()->json([
                "status" => 0
            ]);
        }

        $check = Hash::check($request->password, $profile->user->password);

        if (!$check) {
            return response()->json([
                "status" => 0
            ]);
        }

        if ($profile->profileType->slug == 'collector') {
            $turn = Turn::where('profile_id', $profile->id)->where('end_at', null)->first();
            if (!$turn) {
                $lastTurn = Turn::latest('number')->first();
                $newNumber = $lastTurn->number + 1;
                $now = date('Y-m-d H:i:s');
                $turn = Turn::create([
                    'number' => $newNumber,
                    'profile_id' => $profile->id,
                    'workstation_id' => $request->workstationId,
                    'begin_at' => $now,
                    'voltaCheck' => 0
                ]);
                $turn->reOpen = false;
            } else {
                $turn->reOpen = true;
            }
            $turn->workstation;
        }

        $profile->user->tokens()->delete();

        return response()->json([
            "status" => 1,
            "profile" => $profile,
            "turn" => $turn ?? null,
            "token" => $profile->user->createToken(time())->plainTextToken
        ]);
    }

    public function logout(Request $request): JsonResponse
    {
        Auth::user()->tokens()->delete();
        return response()->json([
            "status" => 1,
            "message" => "Sesion cerrada exitosamente"
        ]);
    }

    public function testServer()
    {
        return response()->json([
            "status" => 1,
            "message" => "Servidor Principal configurado correctamente"
        ]);
    }
}
