-- Backfill business-license certificate data from base_organize.
-- Source JSON example (base_organize.F_PropertyJson):
-- {
--   "foundedTime": 1776182400000,
--   "address": "...",
--   "managerName": "...",
--   "managerTelePhone": "...",
--   "managerMobilePhone": "...",
--   "manageEmail": "..."
-- }
--
-- Idempotent behavior:
-- 1) ftb_certificate_instance: only insert when (businessLicense, subjectId) does not exist.
-- 2) ftb_certificate_instance_business_license_ext: only insert when active ext row does not exist.

-- 1) Backfill certificate instance (organization company -> businessLicense, subjectType=2)
INSERT INTO ftb_certificate_instance (
    F_Id,
    F_CertificateType,
    F_TemplateId,
    F_SubjectType,
    F_SubjectId,
    F_CertificateNo,
    F_IssueDate,
    F_ExpireDate,
    F_ExpireTimestamp,
    F_IsLongTerm,
    F_Status,
    F_CertificateImage,
    F_EnabledMark,
    F_CreatorUserId,
    F_CreatorTime,
    F_LastModifyUserId,
    F_LastModifyTime,
    F_TenantId
)
SELECT
    REPLACE(UUID(), '-', '') AS F_Id,
    'businessLicense' AS F_CertificateType,
    '' AS F_TemplateId,
    2 AS F_SubjectType,
    src.org_id AS F_SubjectId,
    NULL AS F_CertificateNo,
    NULL AS F_IssueDate,
    NULL AS F_ExpireDate,
    NULL AS F_ExpireTimestamp,
    0 AS F_IsLongTerm,
    1 AS F_Status,
    NULL AS F_CertificateImage,
    0 AS F_EnabledMark,
    src.creator_user_id AS F_CreatorUserId,
    COALESCE(src.creator_time, NOW()) AS F_CreatorTime,
    src.last_modify_user_id AS F_LastModifyUserId,
    COALESCE(src.last_modify_time, src.creator_time, NOW()) AS F_LastModifyTime,
    src.tenant_id AS F_TenantId
FROM (
    SELECT
        bo.F_Id AS org_id,
        bo.F_CreatorUserId AS creator_user_id,
        bo.F_CreatorTime AS creator_time,
        bo.F_LastModifyUserId AS last_modify_user_id,
        bo.F_LastModifyTime AS last_modify_time,
        bo.F_TenantId AS tenant_id
    FROM base_organize bo
    WHERE bo.F_Category = 'company'
      AND (bo.F_DeleteMark = 0 OR bo.F_DeleteMark IS NULL)
) src
LEFT JOIN ftb_certificate_instance ci
       ON ci.F_CertificateType = 'businessLicense'
      AND ci.F_SubjectId = src.org_id
WHERE ci.F_Id IS NULL;


-- 2) Backfill business-license ext data from F_PropertyJson
INSERT INTO ftb_certificate_instance_business_license_ext (
    F_Id,
    F_InstanceId,
    F_CompanyName,
    F_CompanyAddress,
    F_LegalRepresentative,
    F_EstablishDate,
    F_BusinessScope,
    F_EnabledMark,
    F_CreatorUserId,
    F_CreatorTime,
    F_LastModifyUserId,
    F_LastModifyTime,
    F_TenantId
)
SELECT
    REPLACE(UUID(), '-', '') AS F_Id,
    ci.F_Id AS F_InstanceId,
    NULLIF(TRIM(org_json.org_name), '') AS F_CompanyName,
    NULLIF(TRIM(org_json.address_raw), '') AS F_CompanyAddress,
    NULLIF(TRIM(org_json.manager_name_raw), '') AS F_LegalRepresentative,
    CASE
        WHEN org_json.founded_time_raw REGEXP '^[0-9]{10,13}$' THEN
            DATE(
                FROM_UNIXTIME(
                    CAST(org_json.founded_time_raw AS UNSIGNED) /
                    (CASE WHEN CHAR_LENGTH(org_json.founded_time_raw) > 10 THEN 1000 ELSE 1 END)
                )
            )
        ELSE NULL
    END AS F_EstablishDate,
    NULLIF(
        TRIM(
            COALESCE(
                org_json.business_scope_raw,
                CONCAT_WS(', ',
                    CASE WHEN NULLIF(TRIM(org_json.manager_phone_raw), '') IS NULL THEN NULL ELSE CONCAT('managerPhone:', NULLIF(TRIM(org_json.manager_phone_raw), '')) END,
                    CASE WHEN NULLIF(TRIM(org_json.manager_mobile_raw), '') IS NULL THEN NULL ELSE CONCAT('managerMobile:', NULLIF(TRIM(org_json.manager_mobile_raw), '')) END,
                    CASE WHEN NULLIF(TRIM(org_json.manager_email_raw), '') IS NULL THEN NULL ELSE CONCAT('managerEmail:', NULLIF(TRIM(org_json.manager_email_raw), '')) END
                )
            )
        ),
        ''
    ) AS F_BusinessScope,
    0 AS F_EnabledMark,
    org_json.creator_user_id AS F_CreatorUserId,
    COALESCE(org_json.creator_time, NOW()) AS F_CreatorTime,
    org_json.last_modify_user_id AS F_LastModifyUserId,
    COALESCE(org_json.last_modify_time, org_json.creator_time, NOW()) AS F_LastModifyTime,
    org_json.tenant_id AS F_TenantId
FROM (
    SELECT
        bo.F_Id AS org_id,
        bo.F_FullName AS org_name,
        bo.F_CreatorUserId AS creator_user_id,
        bo.F_CreatorTime AS creator_time,
        bo.F_LastModifyUserId AS last_modify_user_id,
        bo.F_LastModifyTime AS last_modify_time,
        bo.F_TenantId AS tenant_id,
        CASE WHEN JSON_VALID(bo.F_PropertyJson) THEN JSON_UNQUOTE(JSON_EXTRACT(bo.F_PropertyJson, '$.foundedTime')) END AS founded_time_raw,
        CASE WHEN JSON_VALID(bo.F_PropertyJson) THEN JSON_UNQUOTE(JSON_EXTRACT(bo.F_PropertyJson, '$.address')) END AS address_raw,
        CASE WHEN JSON_VALID(bo.F_PropertyJson) THEN JSON_UNQUOTE(JSON_EXTRACT(bo.F_PropertyJson, '$.managerName')) END AS manager_name_raw,
        CASE WHEN JSON_VALID(bo.F_PropertyJson) THEN JSON_UNQUOTE(JSON_EXTRACT(bo.F_PropertyJson, '$.businessScope')) END AS business_scope_raw,
        CASE WHEN JSON_VALID(bo.F_PropertyJson) THEN JSON_UNQUOTE(JSON_EXTRACT(bo.F_PropertyJson, '$.managerTelePhone')) END AS manager_phone_raw,
        CASE WHEN JSON_VALID(bo.F_PropertyJson) THEN JSON_UNQUOTE(JSON_EXTRACT(bo.F_PropertyJson, '$.managerMobilePhone')) END AS manager_mobile_raw,
        CASE WHEN JSON_VALID(bo.F_PropertyJson) THEN JSON_UNQUOTE(JSON_EXTRACT(bo.F_PropertyJson, '$.manageEmail')) END AS manager_email_raw
    FROM base_organize bo
    WHERE bo.F_Category = 'company'
      AND (bo.F_DeleteMark = 0 OR bo.F_DeleteMark IS NULL)
) org_json
JOIN ftb_certificate_instance ci
  ON ci.F_CertificateType = 'businessLicense'
 AND ci.F_SubjectId = org_json.org_id
 AND ci.F_EnabledMark = 0
LEFT JOIN ftb_certificate_instance_business_license_ext ble
       ON ble.F_InstanceId = ci.F_Id
      AND ble.F_EnabledMark = 0
WHERE ble.F_Id IS NULL;
