-- Create uploads table to track all uploaded media files
CREATE TABLE IF NOT EXISTS uploads (
    id SERIAL PRIMARY KEY,
    filename VARCHAR(255) NOT NULL UNIQUE,
    original_name VARCHAR(255) NOT NULL,
    file_path VARCHAR(500) NOT NULL,
    file_size INTEGER NOT NULL,
    mime_type VARCHAR(100) NOT NULL,
    uploaded_by INTEGER REFERENCES adminusers(id) ON DELETE SET NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Create index for faster queries
CREATE INDEX IF NOT EXISTS idx_uploads_filename ON uploads(filename);
CREATE INDEX IF NOT EXISTS idx_uploads_created_at ON uploads(created_at DESC);
CREATE INDEX IF NOT EXISTS idx_uploads_uploaded_by ON uploads(uploaded_by);

-- Add column to track which entity uses this upload
ALTER TABLE uploads ADD COLUMN IF NOT EXISTS used_in_type VARCHAR(50);
ALTER TABLE uploads ADD COLUMN IF NOT EXISTS used_in_id INTEGER;

-- Create composite index for usage tracking
CREATE INDEX IF NOT EXISTS idx_uploads_usage ON uploads(used_in_type, used_in_id);

COMMENT ON TABLE uploads IS 'Tracks all uploaded media files (images, documents, etc.)';
COMMENT ON COLUMN uploads.filename IS 'Unique filename stored on disk';
COMMENT ON COLUMN uploads.original_name IS 'Original filename from user upload';
COMMENT ON COLUMN uploads.file_path IS 'Relative path to file (e.g., /uploads/image.jpg)';
COMMENT ON COLUMN uploads.file_size IS 'File size in bytes';
COMMENT ON COLUMN uploads.mime_type IS 'MIME type of the file';
COMMENT ON COLUMN uploads.uploaded_by IS 'Admin user who uploaded the file';
COMMENT ON COLUMN uploads.used_in_type IS 'Type of entity using this file (product, blog, portfolio, etc.)';
COMMENT ON COLUMN uploads.used_in_id IS 'ID of the entity using this file';
