<?php
namespace App\Http\Controllers\API\Customer;

use App\Http\Controllers\Controller;
use App\Models\CustomerAddress;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CustomerAddressController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        return response()->json(['addresses' => $request->user()->addresses()->latest()->get()]);
    }

    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'label'        => 'string|max:50',
            'full_name'    => 'required|string|max:255',
            'phone'        => 'required|string|max:20',
            'address_line1' => 'required|string',
            'address_line2' => 'nullable|string',
            'city'         => 'required|string',
            'state'        => 'required|string',
            'country'      => 'required|string',
            'postal_code'  => 'required|string',
            'is_default'   => 'boolean',
        ]);
        $data['user_id'] = $request->user()->id;
        if ($data['is_default'] ?? false) {
            CustomerAddress::where('user_id', $request->user()->id)->update(['is_default' => false]);
        }
        $address = CustomerAddress::create($data);
        return response()->json(['message' => 'Address added.', 'address' => $address], 201);
    }

    public function show(Request $request, int $id): JsonResponse
    {
        return response()->json(['address' => CustomerAddress::where('user_id', $request->user()->id)->findOrFail($id)]);
    }

    public function update(Request $request, int $id): JsonResponse
    {
        $address = CustomerAddress::where('user_id', $request->user()->id)->findOrFail($id);
        $address->update($request->validate(['full_name' => 'sometimes|string', 'phone' => 'sometimes|string', 'address_line1' => 'sometimes|string', 'city' => 'sometimes|string', 'state' => 'sometimes|string', 'country' => 'sometimes|string', 'postal_code' => 'sometimes|string']));
        return response()->json(['message' => 'Address updated.', 'address' => $address]);
    }

    public function destroy(Request $request, int $id): JsonResponse
    {
        CustomerAddress::where('user_id', $request->user()->id)->findOrFail($id)->delete();
        return response()->json(['message' => 'Address deleted.']);
    }

    public function setDefault(Request $request, int $id): JsonResponse
    {
        CustomerAddress::where('user_id', $request->user()->id)->update(['is_default' => false]);
        CustomerAddress::where('user_id', $request->user()->id)->findOrFail($id)->update(['is_default' => true]);
        return response()->json(['message' => 'Default address set.']);
    }
}
