DO $$
BEGIN
    IF EXISTS (
        SELECT 1 FROM pg_constraint WHERE conname = 'fk_purchase_items_expense_nonstock'
    ) THEN
        ALTER TABLE purchase_items
            DROP CONSTRAINT fk_purchase_items_expense_nonstock;
    END IF;
    IF EXISTS (
        SELECT 1 FROM pg_constraint WHERE conname = 'fk_purchase_items_project_flock_kandang'
    ) THEN
        ALTER TABLE purchase_items
            DROP CONSTRAINT fk_purchase_items_project_flock_kandang;
    END IF;
END $$;

DROP INDEX IF EXISTS idx_purchase_items_expense_nonstock_id;
DROP INDEX IF EXISTS idx_purchase_items_project_flock_kandang_id;

ALTER TABLE purchase_items
    DROP COLUMN IF EXISTS expense_nonstock_id,
    DROP COLUMN IF EXISTS project_flock_kandang_id,
    ALTER COLUMN vehicle_number DROP NOT NULL,
    ALTER COLUMN vehicle_number TYPE VARCHAR USING vehicle_number;

ALTER TABLE purchases
    ALTER COLUMN pr_number TYPE VARCHAR USING pr_number,
    ALTER COLUMN po_number TYPE VARCHAR USING po_number,
    ALTER COLUMN created_at DROP DEFAULT,
    ALTER COLUMN updated_at DROP DEFAULT;

ALTER TABLE purchases
    ADD COLUMN credit_term INT NOT NULL DEFAULT 0,
    ADD COLUMN grand_total NUMERIC(15, 3) NOT NULL DEFAULT 0;

ALTER TABLE purchases
    ALTER COLUMN credit_term DROP DEFAULT,
    ALTER COLUMN grand_total DROP DEFAULT;
