CREATE TABLE IF NOT EXISTS project_flock_populations (
    id BIGSERIAL PRIMARY KEY,
    project_flock_kandang_id BIGINT NOT NULL,
    initial_quantity NUMERIC(15, 3) NOT NULL,
    current_quantity NUMERIC(15, 3) NOT NULL,
    reserved_quantity NUMERIC(15, 3),
    created_by BIGINT NOT NULL,
    created_at TIMESTAMPTZ DEFAULT now(),
    updated_at TIMESTAMPTZ DEFAULT now(),
    deleted_at TIMESTAMPTZ
);

-- FOREIGN KEYS (dijalankan setelah semua tabel parent ada)
DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'project_flock_kandangs') THEN
        ALTER TABLE project_flock_populations
            ADD CONSTRAINT fk_project_flock_kandang_id
            FOREIGN KEY (project_flock_kandang_id)
            REFERENCES project_flock_kandangs(id)
            ON DELETE RESTRICT ON UPDATE CASCADE;
    END IF;

    IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'users') THEN
        ALTER TABLE project_flock_populations
            ADD CONSTRAINT fk_created_by
            FOREIGN KEY (created_by)
            REFERENCES users(id)
            ON DELETE RESTRICT ON UPDATE CASCADE;
    END IF;
END $$;

-- INDEXES
CREATE INDEX IF NOT EXISTS idx_project_flock_populations_project_flock_kandang_id ON project_flock_populations (project_flock_kandang_id);

CREATE INDEX IF NOT EXISTS idx_project_flock_populations_created_by ON project_flock_populations (created_by);