CREATE TABLE IF NOT EXISTS project_flock_kandang_uniformity (
    id BIGSERIAL PRIMARY KEY,
    uniformity NUMERIC(15, 3),
    week INT NOT NULL,
    cv NUMERIC(15, 3),
    chick_qty_of_weight NUMERIC(15, 3),
    mean_up NUMERIC(15, 3),
    mean_down NUMERIC(15, 3),
    project_flock_kandang_id BIGINT NOT NULL,
    uniform_qty NUMERIC(15, 3),
    not_uniform_qty NUMERIC(15, 3),
    uniform_date TIMESTAMPTZ,
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW(),
    deleted_at TIMESTAMPTZ,
    created_by BIGINT NOT NULL
);

DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'project_flock_kandangs') THEN
        IF NOT EXISTS (
            SELECT 1 FROM pg_constraint WHERE conname = 'fk_project_flock_kandang_uniformity_project_flock_kandang'
        ) THEN
            EXECUTE
            'ALTER TABLE project_flock_kandang_uniformity
             ADD CONSTRAINT fk_project_flock_kandang_uniformity_project_flock_kandang
             FOREIGN KEY (project_flock_kandang_id)
             REFERENCES project_flock_kandangs(id)
             ON DELETE RESTRICT ON UPDATE CASCADE';
        END IF;
    END IF;

    IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'users') THEN
        IF NOT EXISTS (
            SELECT 1 FROM pg_constraint WHERE conname = 'fk_project_flock_kandang_uniformity_created_by'
        ) THEN
            EXECUTE
            'ALTER TABLE project_flock_kandang_uniformity
             ADD CONSTRAINT fk_project_flock_kandang_uniformity_created_by
             FOREIGN KEY (created_by)
             REFERENCES users(id)
             ON DELETE RESTRICT ON UPDATE CASCADE';
        END IF;
    END IF;
END $$;

CREATE INDEX IF NOT EXISTS idx_project_flock_kandang_uniformity_project_flock_kandang_id
    ON project_flock_kandang_uniformity (project_flock_kandang_id);

CREATE INDEX IF NOT EXISTS idx_project_flock_kandang_uniformity_project_flock_kandang_week
    ON project_flock_kandang_uniformity (project_flock_kandang_id, week);

CREATE INDEX IF NOT EXISTS idx_project_flock_kandang_uniformity_created_by
    ON project_flock_kandang_uniformity (created_by);

CREATE INDEX IF NOT EXISTS idx_project_flock_kandang_uniformity_deleted_at
    ON project_flock_kandang_uniformity (deleted_at);
