CREATE TABLE IF NOT EXISTS project_flock_populations (
    id BIGSERIAL PRIMARY KEY,
    project_chickin_id BIGINT NOT NULL,
    product_warehouse_id BIGINT NOT NULL,
    total_qty NUMERIC(15, 3) NOT NULL,
    total_used_qty NUMERIC(15, 3) DEFAULT 0,
    notes TEXT,
    created_by BIGINT NOT NULL,
    created_at TIMESTAMPTZ DEFAULT now(),
    updated_at TIMESTAMPTZ DEFAULT now(),
    deleted_at TIMESTAMPTZ
);

DO $$
BEGIN
    IF to_regclass('project_chickins') IS NOT NULL THEN
        ALTER TABLE project_flock_populations
            ADD CONSTRAINT fk_project_flock_populations_chickin
            FOREIGN KEY (project_chickin_id)
            REFERENCES project_chickins(id)
            ON DELETE RESTRICT ON UPDATE CASCADE;
    END IF;

    IF to_regclass('product_warehouses') IS NOT NULL THEN
        ALTER TABLE project_flock_populations
            ADD CONSTRAINT fk_project_flock_populations_warehouse
            FOREIGN KEY (product_warehouse_id)
            REFERENCES product_warehouses(id)
            ON DELETE RESTRICT ON UPDATE CASCADE;
    END IF;

    IF to_regclass('users') IS NOT NULL THEN
        ALTER TABLE project_flock_populations
            ADD CONSTRAINT fk_project_flock_populations_created_by
            FOREIGN KEY (created_by)
            REFERENCES users(id)
            ON DELETE RESTRICT ON UPDATE CASCADE;
    END IF;
END $$;

CREATE INDEX IF NOT EXISTS idx_populations_chickin_id ON project_flock_populations (project_chickin_id)
WHERE
    deleted_at IS NULL;

CREATE INDEX IF NOT EXISTS idx_populations_warehouse_id ON project_flock_populations (product_warehouse_id)
WHERE
    deleted_at IS NULL;

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

CREATE INDEX IF NOT EXISTS idx_populations_chickin_deleted ON project_flock_populations (
    project_chickin_id,
    deleted_at
);

CREATE INDEX IF NOT EXISTS idx_populations_deleted_at ON project_flock_populations (deleted_at);

CREATE UNIQUE INDEX IF NOT EXISTS idx_populations_chickin_unique ON project_flock_populations (project_chickin_id)
WHERE
    deleted_at IS NULL;
