<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Address;
use Illuminate\Http\Request;

class AddressController extends Controller
{
    /**
     * List user's addresses.
     */
    public function index(Request $request)
    {
        $addresses = $request->user()->addresses()->orderByDesc('is_default')->get();

        return response()->json(['addresses' => $addresses]);
    }

    /**
     * Create a new address.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'label' => 'sometimes|string|max:50',
            'street' => 'required|string|max:255',
            'unit' => 'nullable|string|max:50',
            'city' => 'required|string|max:100',
            'state' => 'required|string|max:50',
            'zip' => 'required|string|max:20',
            'country' => 'sometimes|string|max:2',
            'delivery_instructions' => 'nullable|string|max:500',
            'is_default' => 'sometimes|boolean',
        ]);

        // If marking as default, unset other defaults
        if (!empty($validated['is_default'])) {
            $request->user()->addresses()->update(['is_default' => false]);
        }

        // If first address, auto-set as default
        if ($request->user()->addresses()->count() === 0) {
            $validated['is_default'] = true;
        }

        $address = $request->user()->addresses()->create($validated);

        return response()->json(['address' => $address], 201);
    }

    /**
     * Update an address.
     */
    public function update(Request $request, Address $address)
    {
        if ($address->user_id !== $request->user()->id) {
            abort(403);
        }

        $validated = $request->validate([
            'label' => 'sometimes|string|max:50',
            'street' => 'sometimes|string|max:255',
            'unit' => 'nullable|string|max:50',
            'city' => 'sometimes|string|max:100',
            'state' => 'sometimes|string|max:50',
            'zip' => 'sometimes|string|max:20',
            'delivery_instructions' => 'nullable|string|max:500',
            'is_default' => 'sometimes|boolean',
        ]);

        if (!empty($validated['is_default'])) {
            $request->user()->addresses()->where('id', '!=', $address->id)->update(['is_default' => false]);
        }

        $address->update($validated);

        return response()->json(['address' => $address->fresh()]);
    }

    /**
     * Delete an address.
     */
    public function destroy(Request $request, Address $address)
    {
        if ($address->user_id !== $request->user()->id) {
            abort(403);
        }

        // Don't allow deleting if it has active subscriptions
        if ($address->subscriptions()->whereIn('status', ['active', 'paused'])->exists()) {
            return response()->json([
                'message' => 'Cannot delete an address with active subscriptions. Update the subscription first.',
            ], 422);
        }

        $address->delete();

        return response()->json(['message' => 'Address deleted.']);
    }
}
