-- Migration: Add slug field to clients table
-- Description: Adds a unique slug field to the clients table for URL-friendly client identification

ALTER TABLE clients
ADD COLUMN slug VARCHAR(255);

-- Add unique index on slug field
CREATE UNIQUE INDEX IF NOT EXISTS idx_clients_slug ON clients(slug);

-- Add comment
COMMENT ON COLUMN clients.slug IS 'URL-friendly slug generated from client name';

-- Update existing records with slugs based on their names
-- Note: This will generate slugs for existing clients
UPDATE clients 
SET slug = LOWER(
    REGEXP_REPLACE(
        REGEXP_REPLACE(name, '[^a-zA-Z0-9\s-]', '', 'g'),
        '\s+', '-', 'g'
    )
)
WHERE slug IS NULL OR slug = '';

-- Handle potential duplicates by appending numbers
WITH numbered_slugs AS (
    SELECT 
        id,
        slug,
        ROW_NUMBER() OVER (PARTITION BY slug ORDER BY created_at) as rn
    FROM clients
    WHERE slug IS NOT NULL
)
UPDATE clients 
SET slug = CASE 
    WHEN ns.rn > 1 THEN ns.slug || '-' || ns.rn
    ELSE ns.slug
END
FROM numbered_slugs ns
WHERE clients.id = ns.id AND ns.rn > 1;

-- Make slug field NOT NULL after populating existing data
ALTER TABLE clients ALTER COLUMN slug SET NOT NULL;
