<?php

namespace App\Http\Controllers;

use App\Repos\PlanRepo;
use App\Services\ResponseService;
use App\Services\ValidationService;
use Illuminate\Http\Request;
use Throwable;

class PlanController extends Controller
{
    public function list() {
        try {
            $result = PlanRepo::list();
            return ResponseService::ok($result);
        } catch (Throwable $error) {
            return ResponseService::handleError($error);
        }
    }

    public function listPaid() {
        try {
            $result = PlanRepo::listPaid();
            return ResponseService::ok($result);
        } catch (Throwable $error) {
            return ResponseService::handleError($error);
        }
    }

    public function read(Request $request, int $id) {
        try {
            $request->merge(compact('id'));
            $rules = [
                'id' => ['required', 'exists:plans,id'],
            ];
            ValidationService::validate($request->all(), $rules);
            $plan = PlanRepo::findByIdOrFail($id);
            return ResponseService::ok($plan);
        } catch (Throwable $error) {
            return ResponseService::handleError($error);
        }
    }

    public function update(Request $request, int $id) {
        try {
            $request->merge(compact('id'));
            $rules = [
                'id' => ['required', 'exists:plans,id'],
                'name' => ['required', 'string'],
                'title' => ['required', 'string'],
                'description' => ['required', 'string'],
                'price' => ['required', 'numeric'],
                'stripePriceId' => [
                    'required_unless:name,free',
                    "string"
                ],
                'publicPageLimit' => ['required', 'integer', 'min:0'],
                'pageCreationLimit' => ['required', 'integer', 'min:0'],
            ];
            ValidationService::validate($request->all(), $rules);
            $planData = [
                'title' => $request->title,
                'description' => $request->description,
                'price' => $request->price,
                'stripe_price_id' => $request->stripePriceId,
                'public_page_limit' => $request->publicPageLimit,
                'page_creation_limit' => $request->pageCreationLimit,
            ];
            PlanRepo::updateByIdOrFail($id, $planData);
            $result = ['updated' => true];
            return ResponseService::ok($result);
        } catch (Throwable $error) {
            return ResponseService::handleError($error);
        }
    }
}
