-- Add and backfill template status for certificate instances.
-- Source field: ftb_store_certificate_photo.F_Status

SET @column_exists := (
    SELECT COUNT(1)
    FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE()
      AND TABLE_NAME = 'ftb_certificate_instance'
      AND COLUMN_NAME = 'F_TemplateStatus'
);

SET @ddl := IF(
    @column_exists > 0,
    'SELECT 1',
    'ALTER TABLE ftb_certificate_instance ADD COLUMN F_TemplateStatus tinyint DEFAULT NULL COMMENT ''store custom template status'' AFTER F_TemplateId'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

UPDATE ftb_certificate_instance ci
LEFT JOIN ftb_store_certificate_photo scp
       ON scp.F_Id = ci.F_TemplateId
SET ci.F_TemplateStatus = scp.F_Status
WHERE ci.F_CertificateType = 'storeCustomCertificate';

UPDATE ftb_certificate_instance
SET F_TemplateStatus = NULL
WHERE F_CertificateType <> 'storeCustomCertificate';