USE IDENTIFIER(:database);

-- Employee Performance table for tracking top performers by department
-- Supports queries like "who are the top employees in X department"
CREATE TABLE IF NOT EXISTS employee_performance (
    -- Employee identification
    employee_id STRING COMMENT 'Unique identifier for the employee',
    employee_name STRING COMMENT 'Full name of the employee',
    store_id STRING COMMENT 'Store where the employee works',
    store_name STRING COMMENT 'Name of the store location',
    department STRING COMMENT 'Primary department where employee works (e.g., Electronics, Footwear, Customer Service)',
    position_title STRING COMMENT 'Job title/position of the employee',
    manager_id STRING COMMENT 'Employee ID of direct manager',
    hire_date DATE COMMENT 'Date when employee was hired',
    employment_status STRING COMMENT 'Current employment status (active, inactive, terminated)',
    
    -- Performance period
    performance_period STRING COMMENT 'Performance measurement period (daily, weekly, monthly, quarterly)',
    period_start_date DATE COMMENT 'Start date of the performance period',
    period_end_date DATE COMMENT 'End date of the performance period',
    
    -- Sales performance metrics
    total_sales_amount DOUBLE COMMENT 'Total sales revenue generated by employee during period',
    total_transactions INT COMMENT 'Number of transactions completed',
    average_transaction_value DOUBLE COMMENT 'Average value per transaction',
    sales_target DOUBLE COMMENT 'Sales target for the period',
    sales_achievement_percentage DOUBLE COMMENT 'Percentage of sales target achieved',
    upsell_cross_sell_revenue DOUBLE COMMENT 'Additional revenue from upselling and cross-selling',
    
    -- Task performance metrics
    total_tasks_assigned INT COMMENT 'Total number of tasks assigned during period',
    total_tasks_completed INT COMMENT 'Number of tasks completed successfully',
    task_completion_rate DOUBLE COMMENT 'Percentage of tasks completed on time',
    average_task_completion_time_minutes INT COMMENT 'Average time to complete tasks',
    overdue_tasks INT COMMENT 'Number of tasks completed past due date',
    high_priority_tasks_completed INT COMMENT 'Number of high/critical priority tasks completed',
    
    -- Quality and customer service metrics
    average_quality_score DOUBLE COMMENT 'Average quality rating for completed tasks (1.0-5.0)',
    customer_satisfaction_score DOUBLE COMMENT 'Average customer satisfaction rating (1.0-5.0)',
    customer_complaints INT COMMENT 'Number of customer complaints received',
    customer_compliments INT COMMENT 'Number of customer compliments received',
    mystery_shopper_score DOUBLE COMMENT 'Mystery shopper evaluation score (1.0-5.0)',
    
    -- Attendance and reliability metrics
    scheduled_hours DOUBLE COMMENT 'Total hours scheduled to work',
    actual_hours_worked DOUBLE COMMENT 'Actual hours worked',
    attendance_rate DOUBLE COMMENT 'Percentage of scheduled shifts attended',
    punctuality_score DOUBLE COMMENT 'On-time arrival rate (1.0-5.0)',
    sick_days_taken INT COMMENT 'Number of sick days taken during period',
    vacation_days_taken INT COMMENT 'Number of vacation days taken during period',
    
    -- Training and development metrics
    training_hours_completed DOUBLE COMMENT 'Hours of training completed during period',
    certifications_earned INT COMMENT 'Number of new certifications earned',
    training_completion_rate DOUBLE COMMENT 'Percentage of required training completed',
    skill_assessment_score DOUBLE COMMENT 'Latest skill assessment score (1.0-5.0)',
    
    -- Team collaboration metrics
    peer_review_score DOUBLE COMMENT 'Average peer review rating (1.0-5.0)',
    mentoring_hours DOUBLE COMMENT 'Hours spent mentoring other employees',
    team_projects_participated INT COMMENT 'Number of team projects participated in',
    leadership_activities INT COMMENT 'Number of leadership activities undertaken',
    
    -- BOPIS and specialized service metrics
    bopis_orders_processed INT COMMENT 'Number of BOPIS orders processed',
    bopis_processing_time_minutes INT COMMENT 'Average time to process BOPIS orders',
    personal_shopping_sessions INT COMMENT 'Number of personal shopping sessions conducted',
    product_knowledge_score DOUBLE COMMENT 'Product knowledge assessment score (1.0-5.0)',
    
    -- Recognition and achievements
    employee_of_month_awards INT COMMENT 'Number of employee of the month awards',
    performance_bonuses_earned DOUBLE COMMENT 'Total performance bonuses earned',
    recognition_points INT COMMENT 'Points earned in employee recognition program',
    peer_nominations INT COMMENT 'Number of peer nominations received',
    
    -- Overall performance indicators
    overall_performance_score DOUBLE COMMENT 'Calculated overall performance score (1.0-5.0)',
    performance_ranking_in_department INT COMMENT 'Ranking within department (1 = top performer)',
    performance_ranking_in_store INT COMMENT 'Ranking within store (1 = top performer)',
    performance_trend STRING COMMENT 'Performance trend (improving, stable, declining)',
    
    -- Goals and development
    goals_set INT COMMENT 'Number of performance goals set for period',
    goals_achieved INT COMMENT 'Number of performance goals achieved',
    development_plan_progress DOUBLE COMMENT 'Progress on individual development plan (percentage)',
    next_promotion_readiness DOUBLE COMMENT 'Readiness for next promotion level (1.0-5.0)',
    
    -- Metadata
    last_performance_review_date DATE COMMENT 'Date of last formal performance review',
    next_performance_review_date DATE COMMENT 'Date of next scheduled performance review',
    created_at TIMESTAMP COMMENT 'Timestamp when record was created',
    updated_at TIMESTAMP COMMENT 'Timestamp when record was last updated',
    created_by STRING COMMENT 'System or user who created the record',
    updated_by STRING COMMENT 'System or user who last updated the record'
)
USING DELTA
COMMENT 'Employee performance tracking table for identifying top performers by department and supporting performance analytics'
TBLPROPERTIES (
    'delta.enableChangeDataFeed' = 'true',
    'delta.autoOptimize.optimizeWrite' = 'true',
    'delta.autoOptimize.autoCompact' = 'true'
);

-- Create views for common top employee queries

-- View for top employees by department (current month)
CREATE OR REPLACE VIEW top_employees_by_department AS
SELECT 
    department,
    store_name,
    employee_id,
    employee_name,
    position_title,
    overall_performance_score,
    performance_ranking_in_department,
    total_sales_amount,
    sales_achievement_percentage,
    task_completion_rate,
    customer_satisfaction_score,
    attendance_rate,
    ROW_NUMBER() OVER (PARTITION BY department ORDER BY overall_performance_score DESC) as dept_rank
FROM employee_performance
WHERE performance_period = 'monthly' 
    AND period_start_date = DATE_TRUNC('month', CURRENT_DATE())
    AND employment_status = 'active'
ORDER BY department, overall_performance_score DESC;

-- View for top sales performers by department
CREATE OR REPLACE VIEW top_sales_performers_by_department AS
SELECT 
    department,
    store_name,
    employee_id,
    employee_name,
    position_title,
    total_sales_amount,
    sales_achievement_percentage,
    average_transaction_value,
    total_transactions,
    upsell_cross_sell_revenue,
    ROW_NUMBER() OVER (PARTITION BY department ORDER BY sales_achievement_percentage DESC) as sales_rank
FROM employee_performance
WHERE performance_period = 'monthly' 
    AND period_start_date = DATE_TRUNC('month', CURRENT_DATE())
    AND employment_status = 'active'
    AND total_sales_amount > 0
ORDER BY department, sales_achievement_percentage DESC;

-- View for top customer service performers by department
CREATE OR REPLACE VIEW top_customer_service_performers AS
SELECT 
    department,
    store_name,
    employee_id,
    employee_name,
    position_title,
    customer_satisfaction_score,
    mystery_shopper_score,
    customer_compliments,
    customer_complaints,
    bopis_orders_processed,
    personal_shopping_sessions,
    ROW_NUMBER() OVER (PARTITION BY department ORDER BY customer_satisfaction_score DESC) as service_rank
FROM employee_performance
WHERE performance_period = 'monthly' 
    AND period_start_date = DATE_TRUNC('month', CURRENT_DATE())
    AND employment_status = 'active'
ORDER BY department, customer_satisfaction_score DESC;

-- View for top task performers by department
CREATE OR REPLACE VIEW top_task_performers_by_department AS
SELECT 
    department,
    store_name,
    employee_id,
    employee_name,
    position_title,
    task_completion_rate,
    total_tasks_completed,
    average_quality_score,
    high_priority_tasks_completed,
    average_task_completion_time_minutes,
    ROW_NUMBER() OVER (PARTITION BY department ORDER BY task_completion_rate DESC, average_quality_score DESC) as task_rank
FROM employee_performance
WHERE performance_period = 'monthly' 
    AND period_start_date = DATE_TRUNC('month', CURRENT_DATE())
    AND employment_status = 'active'
ORDER BY department, task_completion_rate DESC, average_quality_score DESC;

-- View for employee performance summary by department
CREATE OR REPLACE VIEW department_performance_summary AS
SELECT 
    department,
    store_name,
    COUNT(*) as total_employees,
    AVG(overall_performance_score) as avg_performance_score,
    AVG(sales_achievement_percentage) as avg_sales_achievement,
    AVG(task_completion_rate) as avg_task_completion_rate,
    AVG(customer_satisfaction_score) as avg_customer_satisfaction,
    AVG(attendance_rate) as avg_attendance_rate,
    SUM(total_sales_amount) as total_department_sales,
    SUM(total_tasks_completed) as total_tasks_completed,
    SUM(customer_compliments) as total_customer_compliments,
    SUM(customer_complaints) as total_customer_complaints
FROM employee_performance
WHERE performance_period = 'monthly' 
    AND period_start_date = DATE_TRUNC('month', CURRENT_DATE())
    AND employment_status = 'active'
GROUP BY department, store_name
ORDER BY avg_performance_score DESC;

-- View for identifying best associates for personal shopping appointments
-- Focuses on Women's Fashion department with emphasis on personal shopping skills
CREATE OR REPLACE VIEW best_personal_shopping_associates AS
SELECT 
    store_id,
    store_name,
    employee_id,
    employee_name,
    position_title,
    personal_shopping_sessions,
    customer_satisfaction_score,
    product_knowledge_score,
    overall_performance_score,
    average_quality_score,
    customer_compliments,
    customer_complaints,
    sales_achievement_percentage,
    -- Calculate personal shopping expertise score
    ROUND(
        (personal_shopping_sessions * 0.3 + 
         customer_satisfaction_score * 0.25 + 
         product_knowledge_score * 0.25 + 
         overall_performance_score * 0.2) * 20, 2
    ) as personal_shopping_expertise_score,
    -- Availability indicator based on attendance and current workload
    CASE 
        WHEN attendance_rate >= 98.0 AND task_completion_rate >= 95.0 THEN 'Highly Available'
        WHEN attendance_rate >= 95.0 AND task_completion_rate >= 90.0 THEN 'Available'
        ELSE 'Limited Availability'
    END as availability_status,
    ROW_NUMBER() OVER (PARTITION BY store_id ORDER BY 
        personal_shopping_sessions DESC, 
        customer_satisfaction_score DESC, 
        product_knowledge_score DESC
    ) as store_rank
FROM employee_performance
WHERE department = 'Womens Fashion'
    AND performance_period = 'monthly' 
    AND period_start_date = DATE_TRUNC('month', CURRENT_DATE())
    AND employment_status = 'active'
ORDER BY store_id, personal_shopping_sessions DESC, customer_satisfaction_score DESC;

-- View for cross-store personal shopping recommendations
-- Helps managers find the best associates across all locations
CREATE OR REPLACE VIEW top_personal_shopping_associates_all_stores AS
SELECT 
    store_id,
    store_name,
    employee_id,
    employee_name,
    position_title,
    personal_shopping_sessions,
    customer_satisfaction_score,
    product_knowledge_score,
    overall_performance_score,
    -- Calculate comprehensive personal shopping score
    ROUND(
        (personal_shopping_sessions * 0.35 + 
         customer_satisfaction_score * 0.25 + 
         product_knowledge_score * 0.25 + 
         overall_performance_score * 0.15) * 20, 2
    ) as comprehensive_score,
    CASE 
        WHEN personal_shopping_sessions >= 15 AND customer_satisfaction_score >= 4.7 THEN 'Expert'
        WHEN personal_shopping_sessions >= 10 AND customer_satisfaction_score >= 4.5 THEN 'Advanced'
        WHEN personal_shopping_sessions >= 5 AND customer_satisfaction_score >= 4.3 THEN 'Intermediate'
        ELSE 'Beginner'
    END as expertise_level,
    ROW_NUMBER() OVER (ORDER BY 
        personal_shopping_sessions DESC, 
        customer_satisfaction_score DESC, 
        product_knowledge_score DESC
    ) as overall_rank
FROM employee_performance
WHERE department = 'Womens Fashion'
    AND performance_period = 'monthly' 
    AND period_start_date = DATE_TRUNC('month', CURRENT_DATE())
    AND employment_status = 'active'
ORDER BY personal_shopping_sessions DESC, customer_satisfaction_score DESC; 