-- Create labels lookup table
CREATE TABLE labels (
    label text PRIMARY KEY,
    description text NOT NULL
);

-- Seed initial label values
INSERT INTO labels (label, description) VALUES
    ('Ingested', 'Document has been ingested into the system'),
    ('OCR_Processed', 'OCR text extraction completed'),
    ('GenAI_Processed', 'GenAI processing completed'),
    ('Doczy_AI_Completed', 'Doczy.AI processing completed'),
    ('Dashboard_Ready', 'Document ready for dashboard display');

-- Create documentLabels junction table
CREATE TABLE documentLabels (
    id uuid PRIMARY KEY DEFAULT uuid_generate_v7(),
    documentId uuid NOT NULL,
    label text NOT NULL,
    appliedAt timestamp NOT NULL DEFAULT NOW(),
    appliedBy varchar(255) NOT NULL,
    FOREIGN KEY (documentId) REFERENCES documents(id) ON DELETE CASCADE,
    FOREIGN KEY (label) REFERENCES labels(label)
);

-- Indexes for efficient label queries
CREATE INDEX idx_documentlabels_documentid ON documentLabels(documentId);
CREATE INDEX idx_documentlabels_label ON documentLabels(label);
CREATE INDEX idx_documentlabels_appliedat ON documentLabels(appliedAt);
-- Composite index for finding most recent label application
CREATE INDEX idx_documentlabels_document_label_time ON documentLabels(documentId, label, appliedAt DESC);
