-- Add site_settings table for storing configuration
CREATE TABLE IF NOT EXISTS site_settings (
  key VARCHAR(100) PRIMARY KEY,
  settings JSONB NOT NULL DEFAULT '{}',
  createdat TIMESTAMP DEFAULT NOW(),
  updatedat TIMESTAMP DEFAULT NOW()
);

-- Add indexes for better performance
CREATE INDEX IF NOT EXISTS idx_site_settings_key ON site_settings(key);

-- Insert default settings if they don't exist
INSERT INTO site_settings (key, settings, createdat, updatedat)
VALUES 
  ('general', '{}', NOW(), NOW()),
  ('homepage', '{}', NOW(), NOW()),
  ('menu', '{"items":[]}', NOW(), NOW())
ON CONFLICT (key) DO NOTHING;

-- Ensure products table has all necessary columns
ALTER TABLE products 
ADD COLUMN IF NOT EXISTS isbestseller BOOLEAN DEFAULT FALSE,
ADD COLUMN IF NOT EXISTS category VARCHAR(255),
ADD COLUMN IF NOT EXISTS updatedat TIMESTAMP DEFAULT NOW();

-- Ensure portfolioprojects table has all necessary columns
ALTER TABLE portfolioprojects 
ADD COLUMN IF NOT EXISTS category VARCHAR(255),
ADD COLUMN IF NOT EXISTS isactive BOOLEAN DEFAULT TRUE,
ADD COLUMN IF NOT EXISTS updatedat TIMESTAMP DEFAULT NOW();

-- Ensure blogposts table has all necessary columns  
ALTER TABLE blogposts 
ADD COLUMN IF NOT EXISTS metatitle VARCHAR(255),
ADD COLUMN IF NOT EXISTS metadescription TEXT,
ADD COLUMN IF NOT EXISTS updatedat TIMESTAMP DEFAULT NOW();

-- Ensure pages table has all necessary columns
ALTER TABLE pages 
ADD COLUMN IF NOT EXISTS metatitle VARCHAR(255),
ADD COLUMN IF NOT EXISTS metadescription TEXT,
ADD COLUMN IF NOT EXISTS updatedat TIMESTAMP DEFAULT NOW();

-- Ensure adminusers table has all necessary columns
ALTER TABLE adminusers 
ADD COLUMN IF NOT EXISTS name VARCHAR(255),
ADD COLUMN IF NOT EXISTS username VARCHAR(255) UNIQUE,
ADD COLUMN IF NOT EXISTS passwordneverexpires BOOLEAN DEFAULT FALSE,
ADD COLUMN IF NOT EXISTS updatedat TIMESTAMP DEFAULT NOW();

-- Add username for existing users if not exists
UPDATE adminusers 
SET username = LOWER(REGEXP_REPLACE(email, '@.*$', ''))
WHERE username IS NULL;

-- Add name for existing users if not exists
UPDATE adminusers 
SET name = INITCAP(REGEXP_REPLACE(email, '@.*$', ''))
WHERE name IS NULL;

COMMENT ON TABLE site_settings IS 'Stores site-wide configuration settings in JSON format';
COMMENT ON TABLE products IS 'Product catalog with variants and inventory';
COMMENT ON TABLE portfolioprojects IS 'Portfolio showcase projects';
COMMENT ON TABLE blogposts IS 'Blog posts with SEO metadata';
COMMENT ON TABLE pages IS 'Custom pages with SEO metadata';
