-- +goose Up
CREATE TABLE users (
    id         uuid PRIMARY KEY,
    email      text NOT NULL UNIQUE,
    created_at timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE projects (
    id         uuid PRIMARY KEY,
    user_id    uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    name       text NOT NULL,
    created_at timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE provider_accounts (
    id         uuid PRIMARY KEY,
    project_id uuid NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
    provider   text NOT NULL,
    secret_enc text NOT NULL,
    comment    text NOT NULL DEFAULT '',
    created_at timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE templates (
    id         uuid PRIMARY KEY,
    project_id uuid NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
    name       text NOT NULL,
    doc        jsonb NOT NULL,
    version    int  NOT NULL DEFAULT 1,
    created_at timestamptz NOT NULL DEFAULT now(),
    updated_at timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE domains (
    id                  uuid PRIMARY KEY,
    project_id          uuid NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
    provider_account_id uuid NOT NULL REFERENCES provider_accounts(id) ON DELETE CASCADE,
    zone_name           text NOT NULL,
    zone_id             text NOT NULL,
    template_id         uuid REFERENCES templates(id) ON DELETE SET NULL,
    created_at          timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE check_runs (
    id         uuid PRIMARY KEY,
    domain_id  uuid NOT NULL REFERENCES domains(id) ON DELETE CASCADE,
    result     jsonb NOT NULL,
    created_at timestamptz NOT NULL DEFAULT now()
);

-- seed default tenant (Фаза 1B без логина)
INSERT INTO users (id, email)
VALUES ('00000000-0000-0000-0000-000000000001', 'default@local');
INSERT INTO projects (id, user_id, name)
VALUES ('00000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000001', 'default');

-- +goose Down
DROP TABLE check_runs;
DROP TABLE domains;
DROP TABLE templates;
DROP TABLE provider_accounts;
DROP TABLE projects;
DROP TABLE users;
