-- Create roles table
CREATE TABLE IF NOT EXISTS roles (
  id VARCHAR(50) PRIMARY KEY,
  name VARCHAR(100) NOT NULL UNIQUE,
  description TEXT,
  permissions JSONB DEFAULT '{}',
  createdat TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Insert default roles
INSERT INTO roles (id, name, description, permissions) VALUES
  ('role-admin', 'Admin', 'Full system access and management', '{"manage_users": true, "manage_products": true, "manage_orders": true, "manage_content": true, "view_reports": true, "manage_settings": true}'),
  ('role-accountant', 'Accountant', 'Financial and reporting access', '{"view_orders": true, "view_reports": true, "manage_products": false, "manage_users": false}'),
  ('role-sales', 'Sales', 'Product and order management', '{"manage_products": true, "manage_orders": true, "view_reports": true, "manage_users": false}'),
  ('role-cashier', 'Cashier', 'Basic order processing', '{"process_orders": true, "view_products": true, "manage_products": false, "manage_users": false}')
ON CONFLICT (id) DO NOTHING;

-- Update adminusers table to add role and password expiry fields
ALTER TABLE adminusers 
ADD COLUMN IF NOT EXISTS role_id VARCHAR(50) DEFAULT 'role-admin',
ADD COLUMN IF NOT EXISTS password_expires_at TIMESTAMP,
ADD COLUMN IF NOT EXISTS password_never_expires BOOLEAN DEFAULT false,
ADD COLUMN IF NOT EXISTS last_password_change TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
ADD COLUMN IF NOT EXISTS isactive BOOLEAN DEFAULT true,
ADD COLUMN IF NOT EXISTS last_login TIMESTAMP,
ADD COLUMN IF NOT EXISTS created_by VARCHAR(255),
ADD COLUMN IF NOT EXISTS updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP;

-- Add foreign key constraint
ALTER TABLE adminusers
ADD CONSTRAINT fk_role
FOREIGN KEY (role_id) REFERENCES roles(id)
ON DELETE SET NULL;

-- Update existing admin user
UPDATE adminusers 
SET role_id = 'role-admin', 
    password_never_expires = true,
    isactive = true
WHERE email = 'admin@example.com';

-- Create index for better performance
CREATE INDEX IF NOT EXISTS idx_adminusers_role ON adminusers(role_id);
CREATE INDEX IF NOT EXISTS idx_adminusers_email ON adminusers(email);

SELECT 'User roles setup complete' as status;
