-- ============================================================
-- HMM carrier assignments using existing access-group tables.
--
-- Existing tables:
--   HMM_HR_EMPLOYEES
--   HMM_ACCESS_GROUPS
--   HMM_ACCESS_GROUP_MEMBERS
--
-- No new assignment table is created.
-- Korean values are reconstructed from UTF-8 base64 so SQLcl
-- cannot corrupt the literals.
-- Redmine: #730
-- ============================================================

WHENEVER SQLERROR EXIT SQL.SQLCODE
SET DEFINE OFF
SET FEEDBACK ON
SET SERVEROUTPUT ON

MERGE INTO hmm_access_groups dst
USING (
  SELECT
    base.max_group_id + carrier.seq_no AS group_id,
    'CARRIER_' || carrier.carrier_code AS group_code,
    carrier.carrier_code || ' ' ||
      utl_i18n.raw_to_char(
        utl_encode.base64_decode(
          utl_raw.cast_to_raw('7ISg7IKsIOuLtOuLuSDqt7jro7k=')
        ),
        'AL32UTF8'
      ) AS group_name,
    utl_i18n.raw_to_char(
      utl_encode.base64_decode(
        utl_raw.cast_to_raw(
          '642w66qo7JqpIOyEoOyCrCDsoJHqt7wg67CPIOuLtOuLueyekCDqt7jro7k='
        )
      ),
      'AL32UTF8'
    ) || ' (' || carrier.carrier_code || ')' AS description
  FROM (
    SELECT 1 seq_no, 'C001' carrier_code FROM dual
    UNION ALL SELECT 2, 'C002' FROM dual
    UNION ALL SELECT 3, 'C003' FROM dual
    UNION ALL SELECT 4, 'C004' FROM dual
    UNION ALL SELECT 5, 'C005' FROM dual
    UNION ALL SELECT 6, 'C006' FROM dual
    UNION ALL SELECT 7, 'C007' FROM dual
    UNION ALL SELECT 8, 'C008' FROM dual
  ) carrier
  CROSS JOIN (
    SELECT NVL(MAX(group_id), 0) max_group_id
    FROM hmm_access_groups
  ) base
) src
ON (dst.group_code = src.group_code)
WHEN MATCHED THEN UPDATE SET
  dst.group_name = src.group_name,
  dst.description = src.description,
  dst.active_yn = 'Y',
  dst.updated_at = SYSTIMESTAMP
WHEN NOT MATCHED THEN INSERT (
  group_id,
  group_code,
  group_name,
  description,
  active_yn,
  created_at,
  updated_at
) VALUES (
  src.group_id,
  src.group_code,
  src.group_name,
  src.description,
  'Y',
  SYSTIMESTAMP,
  SYSTIMESTAMP
);

MERGE INTO hmm_access_group_members dst
USING (
  SELECT
    access_group.group_id,
    employee.employee_id
  FROM (
    SELECT 'E1002' employee_code, 'CARRIER_C001' group_code FROM dual
    UNION ALL SELECT 'E1002', 'CARRIER_C002' FROM dual
    UNION ALL SELECT 'E1003', 'CARRIER_C003' FROM dual
    UNION ALL SELECT 'E1004', 'CARRIER_C004' FROM dual
    UNION ALL SELECT 'E1005', 'CARRIER_C005' FROM dual
    UNION ALL SELECT 'E1006', 'CARRIER_C006' FROM dual
    UNION ALL SELECT 'E1006', 'CARRIER_C007' FROM dual
    UNION ALL SELECT 'E1007', 'CARRIER_C008' FROM dual
  ) assignment
  JOIN hmm_hr_employees employee
    ON employee.employee_code = assignment.employee_code
   AND employee.employment_status = 'ACTIVE'
  JOIN hmm_access_groups access_group
    ON access_group.group_code = assignment.group_code
   AND access_group.active_yn = 'Y'
) src
ON (
  dst.group_id = src.group_id
  AND dst.employee_id = src.employee_id
)
WHEN NOT MATCHED THEN INSERT (
  group_id,
  employee_id,
  created_at
) VALUES (
  src.group_id,
  src.employee_id,
  SYSTIMESTAMP
);

CREATE OR REPLACE VIEW hmm_carrier_assignments_v AS
SELECT
  employee.employee_id,
  employee.employee_code,
  employee.full_name AS employee_name,
  employee.job_title,
  employee.team_id,
  employee.manager_employee_id,
  manager.employee_code AS manager_employee_code,
  manager.full_name AS manager_name,
  SUBSTR(access_group.group_code, LENGTH('CARRIER_') + 1) AS carrier_code,
  access_group.group_code,
  access_group.group_name
FROM hmm_access_group_members membership
JOIN hmm_access_groups access_group
  ON access_group.group_id = membership.group_id
 AND access_group.active_yn = 'Y'
JOIN hmm_hr_employees employee
  ON employee.employee_id = membership.employee_id
 AND employee.employment_status = 'ACTIVE'
LEFT JOIN hmm_hr_employees manager
  ON manager.employee_id = employee.manager_employee_id
WHERE access_group.group_code LIKE 'CARRIER_C%';

COMMENT ON TABLE hmm_carrier_assignments_v IS
  'ADB employee-to-carrier assignments from HMM_HR_EMPLOYEES, HMM_ACCESS_GROUPS, and HMM_ACCESS_GROUP_MEMBERS. Join relationship: HMM_CARRIER_ASSIGNMENTS_V.CARRIER_CODE joins HMM_RDS_CARRIERS_V.CARRIER_CODE, HMM_RDS_CARRIER_PERF_V.CARRIER_CODE, and HMM_RDS_CARRIER_LATEST_V.CARRIER_CODE.';
COMMENT ON COLUMN hmm_carrier_assignments_v.EMPLOYEE_CODE IS
  'HMM employee code sourced from HMM_HR_EMPLOYEES.EMPLOYEE_CODE. Example: E1002.';
COMMENT ON COLUMN hmm_carrier_assignments_v.MANAGER_EMPLOYEE_CODE IS
  'Direct manager employee code sourced from HMM_HR_EMPLOYEES. Use E1001 to identify the HMM demo manager team.';
COMMENT ON COLUMN hmm_carrier_assignments_v.CARRIER_CODE IS
  'Join Key and Foreign Key to HMM_RDS_CARRIERS_V(CARRIER_CODE), HMM_RDS_CARRIER_PERF_V(CARRIER_CODE), and HMM_RDS_CARRIER_LATEST_V(CARRIER_CODE).';
COMMENT ON COLUMN hmm_carrier_assignments_v.GROUP_CODE IS
  'Existing access-group code in the form CARRIER_C001.';

COMMIT;

DECLARE
  v_group_count      PLS_INTEGER;
  v_member_count     PLS_INTEGER;
  v_assignment_count PLS_INTEGER;
  v_federated_count  PLS_INTEGER;
BEGIN
  SELECT COUNT(*)
  INTO v_group_count
  FROM hmm_access_groups
  WHERE group_code BETWEEN 'CARRIER_C001' AND 'CARRIER_C008'
    AND active_yn = 'Y';

  SELECT COUNT(*)
  INTO v_member_count
  FROM hmm_access_group_members membership
  JOIN hmm_access_groups access_group
    ON access_group.group_id = membership.group_id
  WHERE access_group.group_code BETWEEN 'CARRIER_C001' AND 'CARRIER_C008';

  SELECT COUNT(*)
  INTO v_assignment_count
  FROM hmm_carrier_assignments_v;

  SELECT COUNT(*)
  INTO v_federated_count
  FROM hmm_carrier_assignments_v assignment
  JOIN hmm_rds_carrier_latest_v performance
    ON performance.carrier_code = assignment.carrier_code;

  IF v_group_count != 8
     OR v_member_count != 8
     OR v_assignment_count != 8
     OR v_federated_count != 8 THEN
    RAISE_APPLICATION_ERROR(
      -20081,
      'Expected group/member/assignment/federated counts 8/8/8/8; found '
      || v_group_count || '/'
      || v_member_count || '/'
      || v_assignment_count || '/'
      || v_federated_count
    );
  END IF;
END;
/

SELECT
  assignment.employee_code,
  assignment.employee_name,
  assignment.manager_employee_code,
  assignment.carrier_code,
  performance.carrier_name,
  performance.performance_month,
  performance.revenue_usd,
  performance.risk_level
FROM hmm_carrier_assignments_v assignment
JOIN hmm_rds_carrier_latest_v performance
  ON performance.carrier_code = assignment.carrier_code
ORDER BY assignment.employee_code, assignment.carrier_code;
