<?php

namespace App\Http\Controllers\Api;

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

class AddressController extends Controller
{
    public function index(Request $request)
    {
        $userId = $request->user() ? $request->user()->id : 1;

        $addresses = Address::where('user_id', $userId)
            ->orderByDesc('is_default')
            ->orderByDesc('id')
            ->get();

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

    public function store(Request $request)
    {
        $userId = $request->user() ? $request->user()->id : 1;

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'type' => 'nullable|string|max:50',
            'phone' => 'nullable|string|max:30',
            'address' => 'required|string|max:500',
            'city' => 'nullable|string|max:100',
            'zip' => 'nullable|string|max:20',
            'is_default' => 'nullable|boolean',
        ]);

        $hasAny = Address::where('user_id', $userId)->exists();
        $makeDefault = ($validated['is_default'] ?? false) || !$hasAny;

        if ($makeDefault) {
            Address::where('user_id', $userId)->update(['is_default' => false]);
        }

        $address = Address::create([
            'user_id' => $userId,
            'name' => $validated['name'],
            'type' => $validated['type'] ?? 'Home',
            'phone' => $validated['phone'] ?? null,
            'address' => $validated['address'],
            'city' => $validated['city'] ?? null,
            'zip' => $validated['zip'] ?? null,
            'is_default' => $makeDefault,
        ]);

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

    public function setDefault(Request $request, string $id)
    {
        $userId = $request->user() ? $request->user()->id : 1;

        $address = Address::where('user_id', $userId)->where('id', $id)->firstOrFail();
        Address::where('user_id', $userId)->update(['is_default' => false]);
        $address->update(['is_default' => true]);

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

    public function destroy(Request $request, string $id)
    {
        $userId = $request->user() ? $request->user()->id : 1;

        $address = Address::where('user_id', $userId)->where('id', $id)->firstOrFail();
        $wasDefault = $address->is_default;
        $address->delete();

        if ($wasDefault) {
            $next = Address::where('user_id', $userId)->orderByDesc('id')->first();
            if ($next) {
                $next->update(['is_default' => true]);
            }
        }

        return response()->json([
            'status' => 'success',
        ]);
    }
}
