-- Adjust purchases table to new purchasing schema
ALTER TABLE purchases
    ALTER COLUMN pr_number TYPE VARCHAR(50) USING LEFT(pr_number, 50),
    ALTER COLUMN po_number TYPE VARCHAR(50) USING LEFT(po_number, 50),
    ALTER COLUMN created_at SET DEFAULT now(),
    ALTER COLUMN updated_at SET DEFAULT now();

ALTER TABLE purchases
    DROP COLUMN IF EXISTS credit_term,
    DROP COLUMN IF EXISTS grand_total;

-- Bring purchase_items in line with new requirements
ALTER TABLE purchase_items
    ADD COLUMN IF NOT EXISTS expense_nonstock_id BIGINT,
    ADD COLUMN IF NOT EXISTS project_flock_kandang_id BIGINT;

UPDATE purchase_items
SET vehicle_number = ''
WHERE vehicle_number IS NULL;

ALTER TABLE purchase_items
    ALTER COLUMN vehicle_number TYPE VARCHAR(10) USING LEFT(vehicle_number, 10),
    ALTER COLUMN vehicle_number SET NOT NULL;

DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'expense_nonstocks') THEN
        IF NOT EXISTS (
            SELECT 1 FROM pg_constraint WHERE conname = 'fk_purchase_items_expense_nonstock'
        ) THEN
            EXECUTE
            'ALTER TABLE purchase_items
             ADD CONSTRAINT fk_purchase_items_expense_nonstock
             FOREIGN KEY (expense_nonstock_id)
             REFERENCES expense_nonstocks(id)
             ON DELETE SET NULL ON UPDATE CASCADE';
        END IF;
    END IF;

    IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'project_flock_kandangs') THEN
        IF NOT EXISTS (
            SELECT 1 FROM pg_constraint WHERE conname = 'fk_purchase_items_project_flock_kandang'
        ) THEN
            EXECUTE
            'ALTER TABLE purchase_items
             ADD CONSTRAINT fk_purchase_items_project_flock_kandang
             FOREIGN KEY (project_flock_kandang_id)
             REFERENCES project_flock_kandangs(id)
             ON DELETE SET NULL ON UPDATE CASCADE';
        END IF;
    END IF;
END $$;

CREATE INDEX IF NOT EXISTS idx_purchase_items_expense_nonstock_id
    ON purchase_items (expense_nonstock_id);
CREATE INDEX IF NOT EXISTS idx_purchase_items_project_flock_kandang_id
    ON purchase_items (project_flock_kandang_id);
