CREATE TABLE expense_nonstocks (
    id BIGSERIAL PRIMARY KEY,
    expense_id BIGINT NOT NULL,
    project_flock_kandang_id BIGINT NULL,
    kandang_id BIGINT NULL,
    nonstock_id BIGINT,
    qty NUMERIC(15, 3) NOT NULL,
    unit_price NUMERIC(15, 3) NOT NULL,
    total_price NUMERIC(15, 3) NOT NULL,
    note TEXT NULL
);

-- Tambahkan Foreign Key ke expenses
DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'expenses') THEN
        ALTER TABLE expense_nonstocks
            ADD CONSTRAINT fk_expense_nonstocks_expense_id 
            FOREIGN KEY (expense_id) REFERENCES expenses(id);
    END IF;
END $$;

-- Tambahkan Foreign Key ke project_flock_kandangs
DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'project_flock_kandangs') THEN
        ALTER TABLE expense_nonstocks
            ADD CONSTRAINT fk_expense_nonstocks_kandang_id 
            FOREIGN KEY (project_flock_kandang_id) REFERENCES project_flock_kandangs(id);
    END IF;
END $$;

-- Tambahkan Foreign key ke kandang_id
DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'kandangs') THEN
        ALTER TABLE expense_nonstocks
            ADD CONSTRAINT fk_expense_nonstocks_kandang_id_2 
            FOREIGN KEY (kandang_id) REFERENCES kandangs(id);
    END IF;
END $$;

-- Tambahkan Foreign Key ke nonstocks
DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'nonstocks') THEN
        ALTER TABLE expense_nonstocks
            ADD CONSTRAINT fk_expense_nonstocks_nonstock_id 
            FOREIGN KEY (nonstock_id) REFERENCES nonstocks(id);
    END IF;
END $$;

-- Index
CREATE INDEX idx_expense_nonstocks_expense_id ON expense_nonstocks (expense_id);

CREATE INDEX idx_expense_nonstocks_nonstock_id ON expense_nonstocks (nonstock_id);