-- PROJ-9: Labels, email-label assignments, and auto-label rules.
-- This file is documentation; the actual schema is applied by labelstore.initSchema().

CREATE TABLE IF NOT EXISTS labels (
    id         BIGSERIAL PRIMARY KEY,
    name       VARCHAR(100) NOT NULL,
    color      VARCHAR(7) NOT NULL DEFAULT '#6366f1',
    owner_id   BIGINT REFERENCES users(id) ON DELETE CASCADE,
    tenant_id  BIGINT REFERENCES tenants(id) ON DELETE CASCADE,
    created_at TIMESTAMPTZ DEFAULT NOW(),
    UNIQUE(name, owner_id, tenant_id)
);

CREATE TABLE IF NOT EXISTS email_labels (
    email_id    VARCHAR(64) NOT NULL,
    label_id    BIGINT NOT NULL REFERENCES labels(id) ON DELETE CASCADE,
    assigned_at TIMESTAMPTZ DEFAULT NOW(),
    assigned_by VARCHAR(20) NOT NULL DEFAULT 'user',
    PRIMARY KEY (email_id, label_id)
);

CREATE TABLE IF NOT EXISTS label_rules (
    id               BIGSERIAL PRIMARY KEY,
    condition_field  VARCHAR(30) NOT NULL,
    condition_value  VARCHAR(255) NOT NULL,
    label_id         BIGINT NOT NULL REFERENCES labels(id) ON DELETE CASCADE,
    tenant_id        BIGINT REFERENCES tenants(id) ON DELETE CASCADE,
    created_at       TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_email_labels_label_id ON email_labels(label_id);
CREATE INDEX IF NOT EXISTS idx_label_rules_tenant_id ON label_rules(tenant_id);
