-- Consolidated Bookmann Database Schema
-- This file contains the complete current schema for the Bookmann media library management system

-- Enable pg_trgm extension for fuzzy string matching and partial search
CREATE EXTENSION IF NOT EXISTS pg_trgm;

-- Create library types table
CREATE TABLE library_types (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name VARCHAR(50) UNIQUE NOT NULL,
    description TEXT,
    allowed_extensions TEXT[] NOT NULL, -- Array of allowed file extensions for this type
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Create reading_progress table
CREATE TABLE reading_progress (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    media_item_id UUID NOT NULL REFERENCES media_items(id) ON DELETE CASCADE,
    user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    current_page INTEGER DEFAULT 0,
    total_pages INTEGER,
    last_read_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    UNIQUE(media_item_id, user_id)
);

-- Create media_ratings table (replaces ebook_ratings)
CREATE TABLE media_ratings (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    media_item_id UUID NOT NULL REFERENCES media_items(id) ON DELETE CASCADE,
    user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    rating INTEGER NOT NULL CHECK (rating >= 1 AND rating <= 10), -- 10-point scale for half-star precision
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    UNIQUE(media_item_id, user_id)
);

-- Create media_notes table for user notes on media items
CREATE TABLE media_notes (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    media_item_id UUID NOT NULL REFERENCES media_items(id) ON DELETE CASCADE,
    user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    content TEXT NOT NULL,
    position VARCHAR(100), -- optional position (page:offset or CFI) for standalone notes
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Create media_highlights table for user highlights on media items
CREATE TABLE media_highlights (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    media_item_id UUID NOT NULL REFERENCES media_items(id) ON DELETE CASCADE,
    user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    selection_text TEXT NOT NULL,
    start_position VARCHAR(100), -- position (page:offset or CFI) where highlight starts
    end_position VARCHAR(100),   -- position (page:offset or CFI) where highlight ends
    color VARCHAR(7) DEFAULT '#ffff00', -- hex color code for highlight
    note_id UUID REFERENCES media_notes(id) ON DELETE SET NULL, -- optional associated note
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Note: user_ebook_folders table is replaced by library_folders table
-- Libraries now handle folder management instead of individual users

-- ISBN normalization trigger
-- Automatically normalizes ISBN on insert and update
CREATE OR REPLACE FUNCTION normalize_media_item_isbn() RETURNS TRIGGER AS $$
BEGIN
    IF NEW.isbn IS NOT NULL THEN
        NEW.isbn := normalize_isbn(NEW.isbn);
    END IF;
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER trigger_normalize_media_item_isbn
    BEFORE INSERT OR UPDATE ON media_items
    FOR EACH ROW
    EXECUTE FUNCTION normalize_media_item_isbn();

-- Create indexes for better query performance
CREATE INDEX idx_users_email ON users(email);
CREATE INDEX idx_users_username ON users(username);
CREATE INDEX idx_library_types_name ON library_types(name);
CREATE INDEX idx_refresh_tokens_token ON refresh_tokens(token);
CREATE INDEX idx_refresh_tokens_user_id ON refresh_tokens(user_id);

-- Library indexes
CREATE INDEX idx_libraries_name ON libraries(name);
CREATE INDEX idx_libraries_library_type_id ON libraries(library_type_id);
CREATE INDEX idx_libraries_created_by_admin_id ON libraries(created_by_admin_id);
CREATE INDEX idx_library_folders_library_id ON library_folders(library_id);
CREATE INDEX idx_library_visibility_user_id ON library_visibility(user_id);
CREATE INDEX idx_library_visibility_library_id ON library_visibility(library_id);

-- Media items indexes
CREATE INDEX idx_media_items_title ON media_items(title);
CREATE INDEX idx_media_items_author ON media_items(author);
CREATE INDEX idx_media_items_library_id ON media_items(library_id);
CREATE INDEX idx_media_items_added_by_admin_id ON media_items(added_by_admin_id);
CREATE INDEX idx_media_items_language ON media_items(language);
CREATE INDEX idx_media_items_genre ON media_items(genre);
CREATE INDEX idx_media_items_page_count ON media_items(page_count);
CREATE INDEX idx_media_items_copyright_year ON media_items(copyright_year);
CREATE INDEX idx_media_items_series_order ON media_items(series, series_number);
CREATE INDEX idx_media_items_date_published ON media_items(date_published);

-- GIN indexes for fast fuzzy search using pg_trgm
CREATE INDEX idx_media_items_title_gin ON media_items USING gin (title gin_trgm_ops);
CREATE INDEX idx_media_items_author_gin ON media_items USING gin (author gin_trgm_ops);
CREATE INDEX idx_media_items_series_gin ON media_items USING gin (series gin_trgm_ops);
CREATE INDEX idx_media_items_tags_gin ON media_items USING gin (tags gin_trgm_ops);
CREATE INDEX idx_media_items_contributors_gin ON media_items USING gin (contributors gin_trgm_ops);

-- Progress and ratings indexes
CREATE INDEX idx_reading_progress_media_item_id ON reading_progress(media_item_id);
CREATE INDEX idx_reading_progress_user_id ON reading_progress(user_id);
CREATE INDEX idx_media_ratings_media_item_id ON media_ratings(media_item_id);
CREATE INDEX idx_media_ratings_user_id ON media_ratings(user_id);

-- Notes and highlights indexes
CREATE INDEX idx_media_notes_media_item_id ON media_notes(media_item_id);
CREATE INDEX idx_media_notes_user_id ON media_notes(user_id);
CREATE INDEX idx_media_highlights_media_item_id ON media_highlights(media_item_id);
CREATE INDEX idx_media_highlights_user_id ON media_highlights(user_id);
CREATE INDEX idx_media_highlights_note_id ON media_highlights(note_id);

-- Add comment explaining the rating system
COMMENT ON COLUMN media_ratings.rating IS 'Rating scale 1-10 (odd numbers = half-stars: 1,3,5,7,9 = 0.5,1.5,2.5,3.5,4.5 stars)';

-- Library Type File Extensions Notes:
-- - Ebooks: .epub, .pdf, .mobi, .azw, .azw3, .txt, .rtf, .doc', .docx, .lit', .fb2, .pdb'
-- - Comics: .cbz, .cbr, .cb7, .cbt, .pdf
-- - Manga: .cbz, .cbr, .png, .jpg, .jpeg, .gif, .bmp, .webp (note: manga includes image folders)

-- Role System Notes:
-- - All users default to 'user' role
-- - Admin users can: create/manage libraries and folders, scan media, modify media metadata, delete media, control library visibility
-- - Regular users can: view visible libraries, rate media, track reading progress, create notes and highlights, manage their profile
-- - To create first admin: UPDATE users SET role = 'admin' WHERE email = 'your-admin-email';
-- - Library visibility is controlled through library_visibility table - admins can hide/show libraries per user
-- - Notes and highlights support position data (page:offset or CFI format) for precise location tracking
-- - Highlights can have associated notes for detailed annotations