-- Create uploaded_files table to track all uploaded files
CREATE TABLE IF NOT EXISTS uploaded_files (
    id BIGSERIAL PRIMARY KEY,
    filename VARCHAR(255) NOT NULL,
    file_path VARCHAR(500) NOT NULL UNIQUE,
    file_url VARCHAR(500) NOT NULL,
    file_size BIGINT NOT NULL DEFAULT 0,
    mime_type VARCHAR(100),
    uploaded_by_id BIGINT REFERENCES users(id) ON DELETE SET NULL,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    deleted_at TIMESTAMP WITH TIME ZONE
);

-- Create index for faster lookups
CREATE INDEX IF NOT EXISTS idx_uploaded_files_file_path ON uploaded_files(file_path);
CREATE INDEX IF NOT EXISTS idx_uploaded_files_uploaded_by ON uploaded_files(uploaded_by_id);
CREATE INDEX IF NOT EXISTS idx_uploaded_files_created_at ON uploaded_files(created_at);
CREATE INDEX IF NOT EXISTS idx_uploaded_files_deleted_at ON uploaded_files(deleted_at);

-- Create file_usages table to track where files are used
CREATE TABLE IF NOT EXISTS file_usages (
    id BIGSERIAL PRIMARY KEY,
    file_id BIGINT NOT NULL REFERENCES uploaded_files(id) ON DELETE CASCADE,
    entity_type VARCHAR(100) NOT NULL, -- e.g., 'article', 'player', 'sponsor', 'event', 'contact', 'settings'
    entity_id BIGINT NOT NULL,
    field_name VARCHAR(100), -- e.g., 'image_url', 'logo_url', 'attachments'
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

-- Create indexes for file usage tracking
CREATE INDEX IF NOT EXISTS idx_file_usages_file_id ON file_usages(file_id);
CREATE INDEX IF NOT EXISTS idx_file_usages_entity ON file_usages(entity_type, entity_id);
CREATE UNIQUE INDEX IF NOT EXISTS idx_file_usages_unique ON file_usages(file_id, entity_type, entity_id, field_name);
