<?php

namespace App\Http\Controllers\Billing;

use App\Http\Controllers\ApiController;
use App\Http\Requests\Billing\IndexBillingRequest;
use App\Http\Requests\Billing\StoreBillingProfileRequest;
use App\Http\Requests\Billing\UpdateBillingProfileRequest;
use App\Http\Resources\Billing\BillingProfileResource;
use App\Services\Billing\BillingProfileService;
use Illuminate\Http\Request;

class BillingProfileController extends ApiController
{
    public function __construct(protected BillingProfileService $service) {}

    public function index(IndexBillingRequest $request)
    {
        return $this->successPaginated($this->service->list($request->validated(), $request->user(), $this->tenantId($request)), BillingProfileResource::class, 'Daftar profile tagihan berhasil diambil');
    }

    public function store(StoreBillingProfileRequest $request)
    {
        return $this->created(new BillingProfileResource($this->service->create($request->validated(), $request->user(), $this->tenantId($request))), 'Profile tagihan berhasil dibuat');
    }

    public function show(Request $request, int $id)
    {
        $profile = $this->service->find($id);
        $this->authorizeTenant($request, $profile->tenant_id);

        return $this->success(new BillingProfileResource($profile), 'Detail profile tagihan berhasil diambil');
    }

    public function update(UpdateBillingProfileRequest $request, int $id)
    {
        $profile = $this->service->find($id);
        $this->authorizeTenant($request, $profile->tenant_id);

        return $this->updated(new BillingProfileResource($this->service->update($profile, $request->validated(), $request->user())), 'Profile tagihan berhasil diperbarui');
    }

    public function destroy(Request $request, int $id)
    {
        $profile = $this->service->find($id);
        $this->authorizeTenant($request, $profile->tenant_id);
        $this->service->delete($profile);

        return $this->deleted('Profile tagihan berhasil dihapus');
    }

    private function tenantId(Request $request): ?int
    {
        return $request->attributes->get('tenant_id');
    }

    private function authorizeTenant(Request $request, int $tenantId): void
    {
        abort_unless($request->user()->isMasterAdmin() || $tenantId === $this->tenantId($request), 403);
    }
}
