-- Add split payment tracking to payments table
ALTER TABLE payments ADD COLUMN split_number INTEGER DEFAULT 1;
ALTER TABLE payments ADD COLUMN split_total INTEGER DEFAULT 1;
ALTER TABLE payments ADD COLUMN split_description VARCHAR(255);

-- Add item-specific payment tracking
CREATE TABLE payment_order_items (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    payment_id UUID NOT NULL REFERENCES payments(id) ON DELETE CASCADE,
    order_item_id UUID NOT NULL REFERENCES order_items(id) ON DELETE CASCADE,
    amount DECIMAL(10,2) NOT NULL CHECK (amount >= 0),
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Indexes for payment_order_items
CREATE INDEX idx_payment_order_items_payment_id ON payment_order_items(payment_id);
CREATE INDEX idx_payment_order_items_order_item_id ON payment_order_items(order_item_id);

-- Add refund tracking to payments
ALTER TABLE payments ADD COLUMN refund_amount DECIMAL(10,2) DEFAULT 0.00 CHECK (refund_amount >= 0);
ALTER TABLE payments ADD COLUMN refund_reason VARCHAR(255);
ALTER TABLE payments ADD COLUMN refunded_at TIMESTAMP WITH TIME ZONE;
ALTER TABLE payments ADD COLUMN refunded_by UUID REFERENCES users(id);

-- Add refund tracking to order items with boolean flags
ALTER TABLE order_items ADD COLUMN refund_amount DECIMAL(10,2) DEFAULT 0.00 CHECK (refund_amount >= 0);
ALTER TABLE order_items ADD COLUMN refund_quantity INTEGER DEFAULT 0 CHECK (refund_quantity >= 0);
ALTER TABLE order_items ADD COLUMN is_partially_refunded BOOLEAN DEFAULT FALSE;
ALTER TABLE order_items ADD COLUMN is_fully_refunded BOOLEAN DEFAULT FALSE;
ALTER TABLE order_items ADD COLUMN refund_reason VARCHAR(255);
ALTER TABLE order_items ADD COLUMN refunded_at TIMESTAMP WITH TIME ZONE;
ALTER TABLE order_items ADD COLUMN refunded_by UUID REFERENCES users(id);

-- Indexes for order item refund flags
CREATE INDEX idx_order_items_is_partially_refunded ON order_items(is_partially_refunded);
CREATE INDEX idx_order_items_is_fully_refunded ON order_items(is_fully_refunded);
