<?php

namespace App\Http\Controllers;

use App\Services\MemberService;
use App\Services\AddressService;
use App\Http\Requests\Member\AddressStore;

class AddressController extends Controller
{

    private $addressService;
    private $memberService;

    public function __construct(
        MemberService $memberService,
        AddressService $addressService
    ) {
        $this->memberService = $memberService;
        $this->addressService = $addressService;
        $this->middleware('auth:sanctum');
    }

    public function index()
    {
        $addresses = $this->addressService->getAll();

        return response()->json($addresses, 201);
    }

    public function store(AddressStore $request)
    {
        $member = $this->memberService->get($request->member_id);

        if (!$member) {
            return response()->json(['message' => 'Member not found.'], 404);
        }

        $isSuperAdmin = auth()->user()->hasRole('super_admin');
        $isAdmin = auth()->user()->hasRole('admin');
        $isSuperAdminOrAdmin = $isSuperAdmin || $isAdmin;
        // $isUserDelegated = $member->user_id === auth()->user()->id;

        if (!$isSuperAdmin && !$isAdmin) {
            return response()->json(['message' => 'You have no rights to do this'], 401);
        }

        $request_data = $request->validated();

        // if is an user delegated to work with that member, remove approved_by and approved_at
        $request_data['revisor_id'] = $isSuperAdminOrAdmin ? auth()->user()->id : null;
        $request_data['approved_at'] = $isSuperAdminOrAdmin ? now() : null;

        $address = $this->addressService->save($request_data);

        return response()->json($address, 201);
    }

    public function show($id)
    {
        $address = $this->addressService->get($id);

        return response()->json($address);
    }

    public function destroy($id)
    {
        $isSuperAdmin = auth()->user()->hasRole('super_admin');
        $isAdmin = auth()->user()->hasRole('admin');
        $isSuperAdminOrAdmin = $isSuperAdmin || $isAdmin;

        if (!$isSuperAdminOrAdmin) {
            return response()->json(['message' => 'You have no rights to do this'], 401);
        }

        $this->addressService->delete($id);
        return response()->json(null, 204);
    }
}
