-- Add UNIQUE constraint to slug columns in both books and stationery tables
-- This prevents duplicate slugs and enables slug-based image filename uniqueness

-- First, handle any existing duplicate slugs by appending a suffix
-- For books
UPDATE books b1
SET slug = slug || '-' || book_code::text
WHERE EXISTS (
    SELECT 1 FROM books b2
    WHERE b2.slug = b1.slug
    AND b2.book_code < b1.book_code
);

-- For stationery
UPDATE stationery s1
SET slug = slug || '-' || stationery_code::text
WHERE EXISTS (
    SELECT 1 FROM stationery s2
    WHERE s2.slug = s1.slug
    AND s2.stationery_code < s1.stationery_code
);

-- Add unique constraint to books.slug (if not exists)
DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM pg_constraint 
        WHERE conname = 'books_slug_unique'
    ) THEN
        ALTER TABLE books ADD CONSTRAINT books_slug_unique UNIQUE (slug);
    END IF;
END $$;

-- Add unique constraint to stationery.slug (if not exists)
DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM pg_constraint 
        WHERE conname = 'stationery_slug_unique'
    ) THEN
        ALTER TABLE stationery ADD CONSTRAINT stationery_slug_unique UNIQUE (slug);
    END IF;
END $$;
