CREATE TABLE static_analysis
(
    id             UUID PRIMARY KEY,
    binary_id      UUID                     NOT NULL REFERENCES binaries (id) ON DELETE CASCADE,
    job_id         UUID                     REFERENCES jobs (id) ON DELETE SET NULL,
    engine         VARCHAR(20)              NOT NULL,
    status         VARCHAR(50)              NOT NULL,
    function_count INTEGER                  NOT NULL DEFAULT 0,
    created_at     TIMESTAMP WITH TIME ZONE NOT NULL,
    updated_at     TIMESTAMP WITH TIME ZONE NOT NULL
);

CREATE INDEX idx_static_analysis_binary_id ON static_analysis (binary_id);

CREATE TABLE static_function
(
    id              UUID PRIMARY KEY,
    analysis_id     UUID                     NOT NULL REFERENCES static_analysis (id) ON DELETE CASCADE,
    name            VARCHAR(500)             NOT NULL,
    address         VARCHAR(20)              NOT NULL,
    assembly        TEXT,
    decompiled_code TEXT,
    signature       VARCHAR(1000),
    created_at      TIMESTAMP WITH TIME ZONE NOT NULL
);

CREATE INDEX idx_static_function_analysis_id ON static_function (analysis_id);
CREATE INDEX idx_static_function_name ON static_function (name);

CREATE TABLE static_xref
(
    id        UUID PRIMARY KEY,
    caller_id UUID        NOT NULL REFERENCES static_function (id) ON DELETE CASCADE,
    callee_id UUID        NOT NULL REFERENCES static_function (id) ON DELETE CASCADE,
    type      VARCHAR(20) NOT NULL DEFAULT 'CALL',
    address   VARCHAR(20)
);

CREATE INDEX idx_static_xref_caller_id ON static_xref (caller_id);
CREATE INDEX idx_static_xref_callee_id ON static_xref (callee_id);

ALTER TABLE binaries
    ADD COLUMN static_analysis_done BOOLEAN NOT NULL DEFAULT FALSE;
