CREATE TABLE IF NOT EXISTS project_chickins (
    id BIGSERIAL PRIMARY KEY,
    project_flock_kandang_id BIGINT NOT NULL,
    product_warehouse_id BIGINT NOT NULL,
    chick_in_date DATE NOT NULL,
    usage_qty NUMERIC(15, 3) NOT NULL,
    pending_usage_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_flock_kandangs') IS NOT NULL THEN
        ALTER TABLE project_chickins
            ADD CONSTRAINT fk_project_chickins_kandang
            FOREIGN KEY (project_flock_kandang_id)
            REFERENCES project_flock_kandangs(id)
            ON DELETE RESTRICT ON UPDATE CASCADE;
    END IF;

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

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

CREATE INDEX IF NOT EXISTS idx_chickins_kandang_id ON project_chickins (project_flock_kandang_id)
WHERE
    deleted_at IS NULL;

CREATE INDEX IF NOT EXISTS idx_chickins_warehouse_id ON project_chickins (product_warehouse_id)
WHERE
    deleted_at IS NULL;

CREATE INDEX IF NOT EXISTS idx_chickins_created_by ON project_chickins (created_by);

CREATE INDEX IF NOT EXISTS idx_chickins_kandang_deleted ON project_chickins (
    project_flock_kandang_id,
    deleted_at
);

CREATE INDEX IF NOT EXISTS idx_chickins_deleted_at ON project_chickins (deleted_at);
