<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Http\Requests\Api\CreateOrderRequest;
use App\Http\Resources\Api\OrderResource;
use App\Models\Order;
use App\Services\ActivityLogService;
use App\Services\AdminAlertMailService;
use App\Services\OrderService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class OrderController extends Controller
{
    public function __construct(
        private readonly AdminAlertMailService $adminMails
    ) {
    }

    public function index(Request $request): JsonResponse
    {
        $user = $request->user();
        $query = Order::query()->with('items', 'address');

        if ($user->isAdmin()) {
            $query->orderByDesc('created_at');
        } else {
            $query->where('user_id', $user->id)->orderByDesc('created_at');
        }

        $perPage = min((int) $request->get('per_page', 15), 50);
        $orders = $query->paginate($perPage);

        return response()->json([
            'data' => OrderResource::collection($orders->items()),
            'meta' => [
                'current_page' => $orders->currentPage(),
                'last_page' => $orders->lastPage(),
                'per_page' => $orders->perPage(),
                'total' => $orders->total(),
            ],
        ]);
    }

    public function show(Request $request, Order $order): JsonResponse
    {
        $user = $request->user();
        if (! $user->isAdmin() && $order->user_id !== $user->id) {
            abort(404);
        }
        $order->load('items', 'address', 'user');

        return response()->json(['data' => new OrderResource($order)]);
    }

    public function store(CreateOrderRequest $request, OrderService $orderService): JsonResponse
    {
        $order = $orderService->createFromCart(
            $request->user()->id,
            (int) $request->validated('address_id')
        );

        ActivityLogService::log(
            'order.created',
            $order,
            ['order_id' => $order->id, 'total' => $order->total, 'status' => $order->status],
            "Commande créée #{$order->id} - Total: {$order->total} FCFA",
            $request->user()?->id,
            $request
        );
        $this->adminMails->sendNewOrder($order);

        return response()->json([
            'data' => new OrderResource($order),
            'message' => __('Order created. Proceed to payment.'),
        ], 201);
    }

    public function cancel(Request $request, Order $order): JsonResponse
    {
        $user = $request->user();
        if (! $user->isAdmin() && $order->user_id !== $user->id) {
            abort(404);
        }
        if (! in_array($order->status, [Order::STATUS_PENDING, Order::STATUS_PAID], true)) {
            return response()->json(['message' => __('Order cannot be cancelled.')], 422);
        }
        $oldStatus = $order->status;
        $order->update(['status' => Order::STATUS_CANCELLED]);

        ActivityLogService::log(
            'order.status_changed',
            $order,
            ['order_id' => $order->id, 'from' => $oldStatus, 'to' => Order::STATUS_CANCELLED],
            "Commande #{$order->id} annulée",
            $request->user()?->id,
            $request
        );

        return response()->json([
            'data' => new OrderResource($order->load('items', 'address')),
            'message' => __('Order cancelled.'),
        ]);
    }
}
