CREATE TABLE endpoints (
    id          BIGSERIAL PRIMARY KEY,
    role_label  TEXT NOT NULL,
    host        TEXT NOT NULL,
    port        INT  NOT NULL,
    tls_mode    TEXT NOT NULL CHECK (tls_mode IN ('ssl','starttls','plain')),
    created_at  TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE tasks (
    id               BIGSERIAL PRIMARY KEY,
    name             TEXT NOT NULL,
    src_endpoint_id  BIGINT NOT NULL REFERENCES endpoints(id),
    dst_endpoint_id  BIGINT NOT NULL REFERENCES endpoints(id),
    status           TEXT NOT NULL DEFAULT 'draft',
    folder_mapping   JSONB NOT NULL DEFAULT '{}'::jsonb,
    created_at       TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE accounts (
    id               BIGSERIAL PRIMARY KEY,
    task_id          BIGINT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
    src_login        TEXT NOT NULL,
    src_pass_enc     TEXT NOT NULL,
    dst_login        TEXT NOT NULL,
    dst_pass_enc     TEXT NOT NULL,
    test_src_status  TEXT NOT NULL DEFAULT 'unknown',
    test_dst_status  TEXT NOT NULL DEFAULT 'unknown',
    copied_count     BIGINT NOT NULL DEFAULT 0,
    skipped_count    BIGINT NOT NULL DEFAULT 0,
    error_count      BIGINT NOT NULL DEFAULT 0,
    status           TEXT NOT NULL DEFAULT 'idle'
);

CREATE TABLE runs (
    id            BIGSERIAL PRIMARY KEY,
    task_id       BIGINT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
    started_at    TIMESTAMPTZ NOT NULL DEFAULT now(),
    finished_at   TIMESTAMPTZ,
    status        TEXT NOT NULL DEFAULT 'running',
    total_copied  BIGINT NOT NULL DEFAULT 0,
    total_skipped BIGINT NOT NULL DEFAULT 0,
    total_errors  BIGINT NOT NULL DEFAULT 0
);

CREATE TABLE migrated_messages (
    id          BIGSERIAL PRIMARY KEY,
    account_id  BIGINT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
    folder      TEXT NOT NULL,
    message_key TEXT NOT NULL,
    copied_at   TIMESTAMPTZ NOT NULL DEFAULT now(),
    UNIQUE (account_id, message_key)
);
