<?php

declare(strict_types=1);

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;

/**
 * 收付款综合查询视图（依赖结算收付款表，见 2026_04_19_210000）。
 *
 * dberp_document_queries 见 2026_05_24_140000，须在采购申请、销售报价、结算扩展等表就绪后创建。
 */
return new class extends Migration
{
    public function up(): void
    {
        DB::statement('DROP VIEW IF EXISTS dberp_receipt_payment_queries');
        DB::statement($this->receiptPaymentQueryViewSql());
    }

    public function down(): void
    {
        DB::statement('DROP VIEW IF EXISTS dberp_receipt_payment_queries');
    }

    private function receiptPaymentQueryViewSql(): string
    {
        return <<<'SQL'
CREATE VIEW dberp_receipt_payment_queries AS
SELECT
    (1 * 1000000000) + id AS row_id,
    'receipt' AS direction,
    code,
    status,
    business_time,
    amount,
    customer_id,
    NULL AS supplier_id,
    sales_order_id,
    NULL AS purchase_order_id,
    payment_method_item_id,
    handler_employee_id,
    effective_at,
    voided_at,
    remark
FROM dberp_receipt_orders
UNION ALL
SELECT
    (2 * 1000000000) + id AS row_id,
    'payment' AS direction,
    code,
    status,
    business_time,
    amount,
    NULL AS customer_id,
    supplier_id,
    NULL AS sales_order_id,
    purchase_order_id,
    payment_method_item_id,
    handler_employee_id,
    effective_at,
    voided_at,
    remark
FROM dberp_payment_orders
SQL;
    }
};
