<?php

namespace App\Http\Controllers\Company\RecurringInvoice;

use App\Http\Controllers\Controller;
use App\Http\Requests\RecurringInvoiceRequest;
use App\Http\Resources\RecurringInvoiceResource;
use App\Models\RecurringInvoice;
use App\Services\RecurringInvoiceService;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class RecurringInvoiceController extends Controller
{
    public function __construct(
        private readonly RecurringInvoiceService $recurringInvoiceService,
    ) {}

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index(Request $request)
    {
        $this->authorize('viewAny', RecurringInvoice::class);

        $limit = $request->has('limit') ? $request->limit : 10;

        $recurringInvoices = RecurringInvoice::whereCompany()
            ->applyFilters($request->all())
            ->paginateData($limit);

        return RecurringInvoiceResource::collection($recurringInvoices)
            ->additional(['meta' => [
                'recurring_invoice_total_count' => RecurringInvoice::whereCompany()->count(),
            ]]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(RecurringInvoiceRequest $request)
    {
        $this->authorize('create', RecurringInvoice::class);

        $recurringInvoice = $this->recurringInvoiceService->create($request);

        return new RecurringInvoiceResource($recurringInvoice);
    }

    /**
     * Display the specified resource.
     *
     * @return Response
     */
    public function show(RecurringInvoice $recurringInvoice)
    {
        $this->authorize('view', $recurringInvoice);

        return new RecurringInvoiceResource($recurringInvoice);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  Request  $request
     * @return Response
     */
    public function update(RecurringInvoiceRequest $request, RecurringInvoice $recurringInvoice)
    {
        $this->authorize('update', $recurringInvoice);

        $this->recurringInvoiceService->update($recurringInvoice, $request);

        return new RecurringInvoiceResource($recurringInvoice);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  RecurringInvoice  $recurringInvoice
     * @return Response
     */
    public function delete(Request $request)
    {
        $this->authorize('delete multiple recurring invoices');

        $ids = RecurringInvoice::whereCompany()
            ->whereIn('id', $request->ids)
            ->pluck('id');

        $this->recurringInvoiceService->delete($ids);

        return response()->json([
            'success' => true,
        ]);
    }
}
