-- HR Performance Engine: composite scoring (tasks / CRM / attendance / fines).
-- Separate from Employee Performance (CRM leaderboard).

CREATE TABLE IF NOT EXISTS hr_performance_settings (
  id INT AUTO_INCREMENT PRIMARY KEY,
  weight_tasks DECIMAL(5,4) NOT NULL DEFAULT 0.4000,
  weight_crm DECIMAL(5,4) NOT NULL DEFAULT 0.3000,
  weight_attendance DECIMAL(5,4) NOT NULL DEFAULT 0.2000,
  weight_fines DECIMAL(5,4) NOT NULL DEFAULT 0.1000,
  target_emails INT NOT NULL DEFAULT 100,
  target_response_rate DECIMAL(5,2) NOT NULL DEFAULT 10.00,
  target_positive_replies INT NOT NULL DEFAULT 10,
  target_leads INT NOT NULL DEFAULT 5,
  target_contacts INT NOT NULL DEFAULT 20,
  target_tasks INT NOT NULL DEFAULT 20,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

INSERT INTO hr_performance_settings (id)
SELECT 1 WHERE NOT EXISTS (SELECT 1 FROM hr_performance_settings WHERE id = 1);

CREATE TABLE IF NOT EXISTS hr_performance_snapshots (
  id INT AUTO_INCREMENT PRIMARY KEY,
  employee_id INT NOT NULL,
  period_start DATE NOT NULL,
  period_end DATE NOT NULL,
  score DECIMAL(6,2) NOT NULL DEFAULT 0,
  grade CHAR(1) NOT NULL DEFAULT 'E',
  tasks_norm DECIMAL(6,4) NOT NULL DEFAULT 0,
  crm_norm DECIMAL(6,4) NOT NULL DEFAULT 0,
  attendance_norm DECIMAL(6,4) NOT NULL DEFAULT 0,
  fines_norm DECIMAL(6,4) NOT NULL DEFAULT 0,
  components_json JSON NULL,
  weights_json JSON NULL,
  locked TINYINT(1) NOT NULL DEFAULT 0,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  UNIQUE KEY uq_perf_snap (employee_id, period_start, period_end),
  CONSTRAINT fk_perf_snap_emp FOREIGN KEY (employee_id) REFERENCES employees(id) ON DELETE CASCADE
);

INSERT IGNORE INTO permission_modules (module_key, label, module_group, sort_order) VALUES
  ('hr_performance', 'HR Performance Engine', 'HR', 32);

INSERT IGNORE INTO role_permissions (role_id, module_key, action_key, allowed)
SELECT wr.id, 'hr_performance', pa.action_key, 1
FROM workspace_roles wr
CROSS JOIN permission_actions pa
WHERE wr.slug = 'super-admin'
  AND pa.action_key IN ('read', 'create', 'update', 'delete', 'export');
