BEGIN;

-- 1. Add shipping_date column to sales_order
ALTER TABLE sales_order ADD COLUMN shipping_date TIMESTAMP NULL;

-- 2. Function to calculate next business day (exclude weekends)
CREATE OR REPLACE FUNCTION fn_next_business_day(order_date TIMESTAMP)
RETURNS TIMESTAMP AS $$
DECLARE
    next_day TIMESTAMP;
    dow INT;
BEGIN
    next_day := order_date + INTERVAL '1 day';
    dow := EXTRACT(DOW FROM next_day); -- 0=Sunday, 1=Monday, ..., 6=Saturday
    
    -- Skip weekends
    IF dow = 0 THEN -- Sunday
        next_day := next_day + INTERVAL '1 day';
    ELSIF dow = 6 THEN -- Saturday
        next_day := next_day + INTERVAL '2 days';
    END IF;
    
    RETURN next_day;
END;
$$ LANGUAGE plpgsql;

-- 3. Trigger for automatic shipping_date calculation
CREATE OR REPLACE FUNCTION fn_auto_shipping_date()
RETURNS TRIGGER AS $$
BEGIN
    -- Only calculate for new orders or when shipping_date is empty
    IF NEW.shipping_date IS NULL AND NEW.order_date IS NOT NULL THEN
        NEW.shipping_date := fn_next_business_day(NEW.order_date);
    END IF;
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER trg_auto_shipping_date
    BEFORE INSERT OR UPDATE ON sales_order
    FOR EACH ROW
    EXECUTE FUNCTION fn_auto_shipping_date();

COMMIT;