<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Support\ApiResponse;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class OrderController extends Controller
{
    public function index(): JsonResponse
    {
        $orders = Order::query()->latest()->get();
        return ApiResponse::success($orders, '订单列表获取成功');
    }

    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'merchant_id' => ['required', 'integer'],
            'user_id' => ['nullable', 'integer'],
            'buyer_name' => ['nullable', 'string'],
            'buyer_phone' => ['nullable', 'string'],
            'buyer_email' => ['nullable', 'email'],
            'platform' => ['nullable', 'string'],
            'payment_channel' => ['nullable', 'string'],
            'product_amount' => ['required', 'numeric'],
            'discount_amount' => ['nullable', 'numeric'],
            'shipping_amount' => ['nullable', 'numeric'],
            'pay_amount' => ['required', 'numeric'],
            'remark' => ['nullable', 'string'],
        ]);

        $order = Order::query()->create([
            'merchant_id' => $data['merchant_id'],
            'user_id' => $data['user_id'] ?? null,
            'order_no' => 'ORD' . now()->format('YmdHis') . random_int(1000, 9999),
            'status' => 'pending',
            'platform' => $data['platform'] ?? 'h5',
            'payment_channel' => $data['payment_channel'] ?? 'wechat_pay',
            'payment_status' => 'unpaid',
            'device_type' => $data['platform'] ?? 'h5',
            'product_amount' => $data['product_amount'],
            'discount_amount' => $data['discount_amount'] ?? 0,
            'shipping_amount' => $data['shipping_amount'] ?? 0,
            'pay_amount' => $data['pay_amount'],
            'buyer_name' => $data['buyer_name'] ?? null,
            'buyer_phone' => $data['buyer_phone'] ?? null,
            'buyer_email' => $data['buyer_email'] ?? null,
            'remark' => $data['remark'] ?? null,
        ]);

        return ApiResponse::success($order, '订单创建成功');
    }
}
