-- Migration: Add billed_via_thehub_id to tmodule_times
-- This tracks which Hub order (and indirectly e-conomic order) each time entry was billed through

DO $$
BEGIN
    -- Add billed_via_thehub_id column if it doesn't exist
    IF NOT EXISTS (
        SELECT 1 FROM information_schema.columns 
        WHERE table_name = 'tmodule_times' AND column_name = 'billed_via_thehub_id'
    ) THEN
        ALTER TABLE tmodule_times ADD COLUMN billed_via_thehub_id INTEGER;
        RAISE NOTICE 'Added column billed_via_thehub_id to tmodule_times';
    ELSE
        RAISE NOTICE 'Column billed_via_thehub_id already exists';
    END IF;
    
    -- Add foreign key constraint to tmodule_orders
    IF NOT EXISTS (
        SELECT 1 FROM information_schema.table_constraints 
        WHERE table_name = 'tmodule_times' 
        AND constraint_name = 'tmodule_times_billed_via_thehub_id_fkey'
    ) THEN
        ALTER TABLE tmodule_times 
        ADD CONSTRAINT tmodule_times_billed_via_thehub_id_fkey 
        FOREIGN KEY (billed_via_thehub_id) 
        REFERENCES tmodule_orders(id) 
        ON DELETE SET NULL;
        RAISE NOTICE 'Added foreign key constraint for billed_via_thehub_id';
    ELSE
        RAISE NOTICE 'Foreign key constraint already exists';
    END IF;
    
    -- Add index for faster lookups
    IF NOT EXISTS (
        SELECT 1 FROM pg_indexes 
        WHERE tablename = 'tmodule_times' 
        AND indexname = 'idx_tmodule_times_billed_via_thehub_id'
    ) THEN
        CREATE INDEX idx_tmodule_times_billed_via_thehub_id ON tmodule_times(billed_via_thehub_id);
        RAISE NOTICE 'Created index idx_tmodule_times_billed_via_thehub_id';
    ELSE
        RAISE NOTICE 'Index idx_tmodule_times_billed_via_thehub_id already exists';
    END IF;
END $$;

-- Add comment explaining the column
COMMENT ON COLUMN tmodule_times.billed_via_thehub_id IS 
'Hub order ID that this time entry was billed through. Links to tmodule_orders.id which contains economic_order_number.';
