-- Tables du dictionnaire de données (formulaires dynamiques)

CREATE TABLE IF NOT EXISTS dd_entities (
    id        SERIAL PRIMARY KEY,
    code      TEXT    NOT NULL UNIQUE,
    label     TEXT    NOT NULL DEFAULT '',
    is_active BOOLEAN NOT NULL DEFAULT TRUE
);

CREATE TABLE IF NOT EXISTS dd_fields (
    id          SERIAL PRIMARY KEY,
    entity_id   INTEGER NOT NULL REFERENCES dd_entities(id) ON DELETE CASCADE,
    code        TEXT    NOT NULL,
    label       TEXT    NOT NULL DEFAULT '',
    field_type  TEXT    NOT NULL DEFAULT 'text',
    ui_order    INTEGER,
    is_required BOOLEAN NOT NULL DEFAULT FALSE,
    default_val TEXT,
    UNIQUE (entity_id, code)
);

CREATE TABLE IF NOT EXISTS dd_rules (
    id          SERIAL PRIMARY KEY,
    entity_id   INTEGER NOT NULL REFERENCES dd_entities(id) ON DELETE CASCADE,
    rule_type   TEXT    NOT NULL,
    expression  TEXT,
    message     TEXT,
    active      BOOLEAN NOT NULL DEFAULT TRUE
);

CREATE TABLE IF NOT EXISTS dd_enums (
    id   SERIAL PRIMARY KEY,
    name TEXT NOT NULL UNIQUE
);

CREATE TABLE IF NOT EXISTS dd_enum_values (
    id         SERIAL PRIMARY KEY,
    enum_id    INTEGER NOT NULL REFERENCES dd_enums(id) ON DELETE CASCADE,
    code       TEXT    NOT NULL,
    label      TEXT    NOT NULL DEFAULT '',
    active     BOOLEAN NOT NULL DEFAULT TRUE,
    sort_order INTEGER NOT NULL DEFAULT 0,
    UNIQUE (enum_id, code)
);
