<?php

namespace App\Http\Controllers;

use App\Http\Requests\AddressRequest;
use App\Http\Resources\AddressResource;
use App\Services\AddressService;
use Illuminate\Http\JsonResponse;

class AddressController extends Controller
{
    protected AddressService $addressService;

    public function __construct(AddressService $addressService)
    {
        $this->addressService = $addressService;
    }

    public function showBySource(AddressRequest $request): JsonResponse
    {
        $address = $this->addressService->findBySource($request->validated());

        return $this->successResponse(
            payload: AddressResource::collection($address),
        );
    }

    public function show($id): JsonResponse
    {
        $address = $this->addressService->one($id);

        return $this->successResponse(
            payload: new AddressResource($address),
        );
    }

    public function store(AddressRequest $request): JsonResponse
    {
        $address = $this->addressService->create($request->validated());

        return $this->successResponse(
            payload: new AddressResource($address),
            message: __('messages.created'),
            code:    201,
        );
    }

    public function update(AddressRequest $request, string $id): JsonResponse
    {
        $address = $this->addressService->update($request->validated(), $id);

        return $this->successResponse(
            payload: new AddressResource($address),
            message: __('messages.updated'),
        );
    }

    public function destroy(string $id): JsonResponse
    {
        $this->addressService->delete($id);

        return $this->successResponse(
            message: __('messages.deleted'),
            code:    204,
        );
    }

    //

    public function showPrimaryBySource(AddressRequest $request): JsonResponse
    {
        $address = $this->addressService->findPrimaryBySource($request->validated());

        return $this->successResponse(
            payload: new AddressResource($address),
        );
    }
}
