<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * 创建电商核心表
     *
     * 依据《电子商务法》和《消费者权益保护法》，
     * 电商平台需包含商品管理、订单管理、购物车、支付交易、
     * 退款、商家认证、电子合同等模块。
     */
    public function up(): void
    {
        // 商家表
        Schema::create('ecommerce_merchants', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained('users')->cascadeOnDelete()->comment('关联用户');
            $table->string('shop_name', 100)->comment('店铺名称');
            $table->string('shop_logo', 255)->nullable()->comment('店铺 Logo');
            $table->string('type', 20)->default('individual')->comment('类型：enterprise/individual');
            $table->string('company_name', 200)->nullable()->comment('企业名称');
            $table->string('credit_code', 50)->nullable()->comment('统一社会信用代码');
            $table->string('legal_person_name', 50)->nullable()->comment('法人姓名');
            $table->text('legal_person_id_card')->nullable()->comment('法人身份证号（加密）');
            $table->string('business_license', 255)->nullable()->comment('营业执照');
            $table->string('contact_name', 50)->nullable()->comment('联系人');
            $table->text('contact_phone')->nullable()->comment('联系电话（加密）');
            $table->string('verification_status', 20)->default('pending')->comment('认证状态：pending/verified/rejected/expired');
            $table->text('verification_remark')->nullable()->comment('审核备注');
            $table->timestamp('verified_at')->nullable()->comment('认证通过时间');
            $table->tinyInteger('status')->default(1)->comment('状态：1=正常 0=禁用');
            $table->timestamps();
            $table->softDeletes();
            $table->index('verification_status');
        });

        // 商品分类表
        Schema::create('ecommerce_categories', function (Blueprint $table) {
            $table->id();
            $table->string('name', 100)->comment('分类名称');
            $table->foreignId('parent_id')->nullable()->constrained('ecommerce_categories')->nullOnDelete()->comment('上级分类');
            $table->string('icon', 255)->nullable()->comment('分类图标');
            $table->integer('sort')->default(0)->comment('排序');
            $table->tinyInteger('status')->default(1)->comment('状态');
            $table->timestamps();
        });

        // 商品表
        Schema::create('ecommerce_products', function (Blueprint $table) {
            $table->id();
            $table->foreignId('merchant_id')->constrained('ecommerce_merchants')->cascadeOnDelete()->comment('商家');
            $table->foreignId('category_id')->nullable()->constrained('ecommerce_categories')->nullOnDelete()->comment('分类');
            $table->string('name', 200)->comment('商品名称');
            $table->string('subtitle', 200)->nullable()->comment('副标题');
            $table->string('sku', 50)->unique()->comment('商品编码');
            $table->string('brand', 50)->nullable()->comment('品牌');
            $table->decimal('price', 10, 2)->comment('售价');
            $table->decimal('original_price', 10, 2)->nullable()->comment('原价');
            $table->decimal('cost_price', 10, 2)->nullable()->comment('成本价');
            $table->integer('stock')->default(0)->comment('库存');
            $table->integer('min_stock')->default(10)->comment('库存预警阈值');
            $table->integer('sales')->default(0)->comment('销量');
            $table->json('images')->nullable()->comment('商品图片');
            $table->text('description')->nullable()->comment('商品描述');
            $table->json('specs')->nullable()->comment('规格参数');
            $table->string('unit', 20)->nullable()->comment('单位');
            $table->decimal('weight', 8, 2)->nullable()->comment('重量（kg）');
            $table->tinyInteger('status')->default(1)->comment('状态：1=上架 0=下架');
            $table->boolean('is_refundable')->default(true)->comment('是否支持退款');
            $table->boolean('is_new')->default(false)->comment('是否新品');
            $table->boolean('is_hot')->default(false)->comment('是否热销');
            $table->timestamp('listed_at')->nullable()->comment('上架时间');
            $table->timestamps();
            $table->softDeletes();
            $table->index(['merchant_id', 'status']);
            $table->index('category_id');
        });

        // 商品规格表
        Schema::create('ecommerce_product_specs', function (Blueprint $table) {
            $table->id();
            $table->foreignId('product_id')->constrained('ecommerce_products')->cascadeOnDelete()->comment('商品');
            $table->string('name', 100)->comment('规格名称');
            $table->string('value', 100)->comment('规格值');
            $table->decimal('price', 10, 2)->nullable()->comment('规格价格（覆盖商品价格）');
            $table->integer('stock')->default(0)->comment('规格库存');
            $table->string('sku', 50)->nullable()->comment('规格编码');
            $table->timestamps();
            $table->index('product_id');
        });

        // 订单表
        Schema::create('ecommerce_orders', function (Blueprint $table) {
            $table->id();
            $table->string('order_no', 32)->unique()->comment('订单号');
            $table->foreignId('user_id')->constrained('users')->cascadeOnDelete()->comment('用户');
            $table->foreignId('merchant_id')->nullable()->constrained('ecommerce_merchants')->nullOnDelete()->comment('商家');
            $table->string('status', 20)->default('pending')->comment('状态：pending/paid/shipped/delivered/completed/cancelled/refunding/refunded');
            $table->decimal('total_amount', 10, 2)->comment('商品总金额');
            $table->decimal('discount_amount', 10, 2)->default(0)->comment('优惠金额');
            $table->decimal('freight_amount', 10, 2)->default(0)->comment('运费');
            $table->decimal('pay_amount', 10, 2)->comment('实付金额');
            $table->string('coupon_code', 50)->nullable()->comment('优惠券码');
            $table->foreignId('coupon_id')->nullable()->constrained('coupons')->nullOnDelete()->comment('优惠券');
            $table->string('payment_method', 30)->nullable()->comment('支付方式：wechat/alipay/unipay');
            $table->string('transaction_id', 100)->nullable()->comment('交易流水号');
            $table->timestamp('paid_at')->nullable()->comment('支付时间');
            $table->timestamp('shipped_at')->nullable()->comment('发货时间');
            $table->timestamp('delivered_at')->nullable()->comment('签收时间');
            $table->timestamp('completed_at')->nullable()->comment('完成时间');
            $table->timestamp('cancelled_at')->nullable()->comment('取消时间');
            $table->string('cancel_reason', 255)->nullable()->comment('取消原因');
            $table->text('remark')->nullable()->comment('订单备注');
            $table->string('buyer_ip', 45)->nullable()->comment('购买 IP');
            $table->timestamps();
            $table->softDeletes();
            $table->index(['user_id', 'status']);
            $table->index('paid_at');
        });

        // 订单商品明细表
        Schema::create('ecommerce_order_items', function (Blueprint $table) {
            $table->id();
            $table->foreignId('order_id')->constrained('ecommerce_orders')->cascadeOnDelete()->comment('订单');
            $table->foreignId('product_id')->nullable()->constrained('ecommerce_products')->nullOnDelete()->comment('商品');
            $table->string('product_name', 200)->comment('商品名称（快照）');
            $table->string('product_image', 255)->nullable()->comment('商品图片（快照）');
            $table->string('product_sku', 50)->nullable()->comment('商品编码（快照）');
            $table->decimal('price', 10, 2)->comment('单价');
            $table->integer('quantity')->comment('数量');
            $table->decimal('subtotal', 10, 2)->comment('小计');
            $table->string('spec_name', 100)->nullable()->comment('规格名称');
            $table->foreignId('spec_id')->nullable()->constrained('ecommerce_product_specs')->nullOnDelete()->comment('规格');
            $table->timestamps();
        });

        // 收货地址表
        Schema::create('ecommerce_addresses', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained('users')->cascadeOnDelete()->comment('用户');
            $table->string('receiver_name', 50)->comment('收货人姓名');
            $table->text('receiver_phone')->comment('收货人手机号（加密）');
            $table->string('province', 30)->comment('省');
            $table->string('city', 30)->comment('市');
            $table->string('district', 30)->comment('区/县');
            $table->string('detail', 255)->comment('详细地址');
            $table->string('postal_code', 10)->nullable()->comment('邮政编码');
            $table->boolean('is_default')->default(false)->comment('是否默认地址');
            $table->string('tag', 20)->nullable()->comment('标签：home/company/school');
            $table->timestamps();
            $table->softDeletes();
            $table->index('user_id');
        });

        // 订单收货地址快照表
        Schema::create('ecommerce_order_addresses', function (Blueprint $table) {
            $table->id();
            $table->foreignId('order_id')->unique()->constrained('ecommerce_orders')->cascadeOnDelete()->comment('订单');
            $table->string('receiver_name', 50)->comment('收货人姓名');
            $table->text('receiver_phone')->comment('收货人手机号（加密）');
            $table->string('province', 30)->comment('省');
            $table->string('city', 30)->comment('市');
            $table->string('district', 30)->comment('区/县');
            $table->string('detail', 255)->comment('详细地址');
            $table->string('postal_code', 10)->nullable()->comment('邮政编码');
            $table->timestamps();
        });

        // 退款/售后表
        Schema::create('ecommerce_refunds', function (Blueprint $table) {
            $table->id();
            $table->foreignId('order_id')->constrained('ecommerce_orders')->cascadeOnDelete()->comment('订单');
            $table->foreignId('user_id')->constrained('users')->cascadeOnDelete()->comment('用户');
            $table->string('refund_no', 32)->unique()->comment('退款单号');
            $table->string('type', 30)->comment('退款类型：no_reason/quality/wrong_item/not_as_described/fraud');
            $table->string('status', 20)->default('pending')->comment('状态：pending/approved/refunding/refunded/rejected');
            $table->decimal('refund_amount', 10, 2)->comment('退款金额');
            $table->decimal('compensation_amount', 10, 2)->default(0)->comment('赔偿金额（退一赔三）');
            $table->string('reason', 500)->nullable()->comment('退款原因');
            $table->json('evidence')->nullable()->comment('凭证图片');
            $table->string('reject_reason', 500)->nullable()->comment('拒绝原因');
            $table->timestamp('refunded_at')->nullable()->comment('退款到账时间');
            $table->timestamps();
            $table->index(['order_id', 'status']);
        });

        // 电子合同表
        Schema::create('ecommerce_contracts', function (Blueprint $table) {
            $table->id();
            $table->foreignId('order_id')->constrained('ecommerce_orders')->cascadeOnDelete()->comment('订单');
            $table->string('contract_no', 32)->unique()->comment('合同编号');
            $table->text('content')->comment('合同内容');
            $table->string('hash', 64)->comment('合同哈希（防篡改）');
            $table->string('buyer_signature', 128)->nullable()->comment('买家签名');
            $table->string('seller_signature', 128)->nullable()->comment('卖家签名');
            $table->string('sign_algorithm', 30)->default('HMAC-SHA256')->comment('签名算法');
            $table->timestamp('signed_at')->nullable()->comment('签署时间');
            $table->string('signer_ip', 45)->nullable()->comment('签署 IP');
            $table->timestamps();
        });

        // 购物车表
        Schema::create('ecommerce_carts', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained('users')->cascadeOnDelete()->comment('用户');
            $table->foreignId('product_id')->constrained('ecommerce_products')->cascadeOnDelete()->comment('商品');
            $table->foreignId('spec_id')->nullable()->constrained('ecommerce_product_specs')->nullOnDelete()->comment('规格');
            $table->integer('quantity')->default(1)->comment('数量');
            $table->boolean('selected')->default(true)->comment('是否选中');
            $table->timestamps();
            $table->unique(['user_id', 'product_id', 'spec_id'], 'uk_cart');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('ecommerce_carts');
        Schema::dropIfExists('ecommerce_contracts');
        Schema::dropIfExists('ecommerce_refunds');
        Schema::dropIfExists('ecommerce_order_addresses');
        Schema::dropIfExists('ecommerce_order_items');
        Schema::dropIfExists('ecommerce_orders');
        Schema::dropIfExists('ecommerce_addresses');
        Schema::dropIfExists('ecommerce_product_specs');
        Schema::dropIfExists('ecommerce_products');
        Schema::dropIfExists('ecommerce_categories');
        Schema::dropIfExists('ecommerce_merchants');
    }
};