<?php

namespace App\Http\Controllers;

use App\Http\Resources\AppointmentResource;
use App\Models\Appointment;
use App\Http\Requests\StoreAppointmentRequest;
use App\Http\Requests\UpdateAppointmentRequest;
use PHPUnit\Runner\ErrorException;

class AppointmentController extends Controller
{
    public function index()
    {
        return response()->json(AppointmentResource::collection(Appointment::all()));
    }

    public function store(StoreAppointmentRequest $request)
    {
        $fields = $request->validated();

        $appointment = Appointment::create($fields);

        return response()->json([
            "appointment" => new AppointmentResource($appointment)
        ], 201);
    }

    public function show($id)
    {
        $appointment = Appointment::with('category')->find($id);

        if ($appointment) {
            return new AppointmentResource($appointment);
        } else {
            return response()->json(['message' => 'Appointment not found'], 404);
        }
    }

    public function update(UpdateAppointmentRequest $request, $id)
    {
        $appointment = Appointment::find($id);

        if (!$appointment) {
            return response()->json(['message' => 'Appointment not found'], 404);
        } elseif ($appointment->is_valid) {
            return response()->json(['message' => 'Cannot update a validated appointment'], 403);
        }

        $fields = $request->validated();

        $appointment->update($fields);

        return response()->json(["appointment" => new AppointmentResource($appointment)], 200);
    }

    public function destroy($id)
    {
        $appointment = Appointment::find($id);

        if (!$appointment) {
            return response()->json(['message' => 'Appointment not found'], 404);
        } elseif ($appointment->is_valid) {
            return response()->json(['message' => 'Cannot delete a validated appointment'], 403);
        }

        $appointment->delete();
        return response()->json(['message' => 'Appointment deleted successfully'], 200);
    }

    public function validation($id)
    {
        // Find restitution by ID
        $appointment = Appointment::find($id);

        if (!$appointment) {
            return response()->json(['message' => 'Appointment not found'], 404);
        } elseif ($appointment->is_valid) {
            return response()->json(['error' => 'Appointment is already validated'], 400);
        }

        $appointment->update([
            'is_valid' => true,
            'validation_date' => now(),
        ]);

        return response()->json(["appointment" => new AppointmentResource($appointment)], 200);
    }
}
