<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Models\Shop\Product\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class CommentController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return response()->rest(
            DB::table('comments')->where('user_id', auth()->id())->get()
        );
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'product_id' => ['required', 'integer', 'exists:products,id'],
            'comment' => ['required', 'string'],
        ]);

        if ($validator->fails()) {
            return response()->rest($validator->messages()->get('*'), 400, 'Validation failed');
        }

        $user = auth()->user();

        $product = Product::find($request->product_id);
        $product->commentAsUser($user, strip_tags($request->comment));

        return response()->rest();
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'comment_id' => ['required', 'integer', 'exists:comments,id'],
            'comment' => ['required', 'string'],
        ]);

        if ($validator->fails()) {
            return response()->rest($validator->messages()->get('*'), 400, []);
        }

        DB::table('comments')->where('id', $request->comment_id)->update([
            'comment' => strip_tags($request->comment),
        ]);

        return response()->rest();
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $validator = Validator::make($request->all(), ['comment_id' => ['required', 'integer']]);

        if ($validator->fails()) {
            return response()->rest($validator->messages()->get('*'), 400, []);
        }

        DB::table('comments')->where('id', $request->comment_id)->delete();

        return response()->rest();
    }
}
