-- Create batch status ENUM type
CREATE TYPE batch_status AS ENUM (
    'processing',       -- Currently processing
    'completed',        -- All documents processed (may have individual failures)
    'failed',           -- Batch-level failure (ZIP corrupt, etc.)
    'cancelled'         -- Cancelled by user
);

-- Create batch uploads table
CREATE TABLE batch_uploads (
    id uuid PRIMARY KEY DEFAULT uuid_generate_v7(),
    client_id varchar(255) NOT NULL,
    original_filename text NOT NULL,
    
    -- Essential batch metrics
    total_documents integer NOT NULL,
    processed_documents integer NOT NULL DEFAULT 0,
    failed_documents integer NOT NULL DEFAULT 0,
    invalid_type_documents integer NOT NULL DEFAULT 0,
    
    -- Status and progress
    status batch_status NOT NULL DEFAULT 'processing',
    progress_percent integer NOT NULL DEFAULT 0,
    
    -- Failed document filenames (JSON array)
    failed_filenames jsonb DEFAULT '[]'::jsonb,
    
    -- Timestamps
    created_at timestamp NOT NULL DEFAULT NOW(),
    completed_at timestamp,
    
    FOREIGN KEY (client_id) REFERENCES clients(clientId)
);

-- Create indexes for efficient queries
CREATE INDEX idx_batch_uploads_client_id ON batch_uploads(client_id);
CREATE INDEX idx_batch_uploads_status ON batch_uploads(status);

-- Add batch_id to documents table
ALTER TABLE documents ADD COLUMN batch_id uuid NULL;
ALTER TABLE documents ADD FOREIGN KEY (batch_id) REFERENCES batch_uploads(id);

-- Create index on batch_id for efficient batch document queries
CREATE INDEX idx_documents_batch_id ON documents(batch_id);