<?php
namespace App\Http\Controllers\Api;

use App\Models\Rating;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Exception;
use Termwind\Components\Raw;

class RatingController
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $rating = Rating::all();
        return response()->json($rating, 200, ['Content-Type' => 'application/json; charset=UTF-8'], JSON_UNESCAPED_UNICODE);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function getByUser(Request $request) {
      try {
        $ratingResult = Rating::where('id_usuarios', $request->id_usuarios)
                              ->where('id_noticias', $request->id_noticias)
                              ->get();
        if(!$ratingResult) {
          return response()->json(['message' => 'No se encontró la calificación'], 404);
        }
        return response()->json($ratingResult, 200, ['Content-Type' => 'application/json; charset=UTF-8'], JSON_UNESCAPED_UNICODE);
      } catch (Exception $exeption) {
        return response()->json(['message' => 'Error al hacer la consulta'], 500);
      }
    }

    public function createRating(Request $request) {
      $ratingValidated = Validator::make($request->all(), [
        "id_usuarios" => 'required|uuid',
        "id_noticias" => 'required|uuid',
        "valor" => 'required|integer'
      ]);
      if ($ratingValidated->fails()) {
        return response()->json([
          'message' => 'Validation failed',
          'errors' => $ratingValidated->errors() ],
          422);
      }
      try {
        $ratingCreated = Rating::insert([
          'id_noticias' => $request->id_noticias,
          'id_usuarios' => $request->id_usuarios,
          'valor' => $request->valor
        ]);
        return response()->json(
          ['message' => 'La calificación se ha creado'],
          201
        );
      }catch (Exception $exeption) {
        return response()->json(
          ['message' => 'La creación ha fallado:'. $exeption->getMessage()],
          500
        );

    }


    }


        //


    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }
}
