<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Http\Resources\ContactResource;
use App\Models\Contact;
use App\Support\ApiResponse;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;

class ContactController extends Controller
{
    public function index()
    {
        Gate::authorize('viewAny', Contact::class);

        return ContactResource::collection(Contact::all());
    }

    public function store(Request $request)
    {
        Gate::authorize('create', Contact::class);
        try {
            DB::beginTransaction();
            $item = new Contact;
            $data = $request->all();
            $data['created_by'] = Auth::user()->id;
            $contact = $item->create($data);
            DB::commit();
        } catch (Exception $exception) {
            return ApiResponse::response(message: $exception->getMessage(), status: 419);
        }

        return new ContactResource($contact);
    }

    public function show(Contact $contact)
    {
        Gate::authorize('view', $contact);

        return new ContactResource($contact);
    }

    public function update(Request $request, Contact $contact)
    {
        Gate::authorize('update', $contact);
        try {
            DB::beginTransaction();
            $data = $request->all();
            $data['updated_by'] = Auth::user()->id;
            $contact->update($data);
            DB::commit();
        } catch (Exception $exception) {
            return ApiResponse::response(message: $exception->getMessage(), status: 419);
        }

        return new ContactResource($contact);
    }

    public function destroy(Contact $contact)
    {
        Gate::authorize('delete', $contact);
        try {
            DB::beginTransaction();
            DB::commit();
        } catch (Exception $exception) {
            return ApiResponse::response(message: $exception->getMessage(), status: 419);
        }

        return ApiResponse::success(message: 'با موفقیت حذف شد');
    }
}
