#!/usr/bin/env tsx
/**
 * 验证 works 表的时间字段格式
 */
import { initDatabase } from '../models/index.js';
import { AppDataSource } from '../models/index.js';
import { Work } from '../models/entities/Work.js';
import { logger } from '../utils/logger.js';

async function verifyWorkTimestamp() {
  try {
    await initDatabase();
    logger.info('数据库连接已初始化');

    const repo = AppDataSource.getRepository(Work);
    
    // 查询最新的作品
    const work = await repo.findOne({
      where: {},
      order: { id: 'DESC' },
      select: ['id', 'title', 'createdAt', 'updatedAt']
    });

    if (work) {
      logger.info(`\n作品 ID: ${work.id}`);
      logger.info(`标题: ${work.title}`);
      logger.info(`createdAt (Date对象): ${work.createdAt}`);
      logger.info(`updatedAt (Date对象): ${work.updatedAt}`);
      
      // 格式化为字符串
      const createdAtStr = work.createdAt instanceof Date 
        ? work.createdAt.toISOString().replace('T', ' ').substring(0, 19)
        : String(work.createdAt);
      const updatedAtStr = work.updatedAt instanceof Date
        ? work.updatedAt.toISOString().replace('T', ' ').substring(0, 19)
        : String(work.updatedAt);
      
      logger.info(`createdAt (格式化): ${createdAtStr}`);
      logger.info(`updatedAt (格式化): ${updatedAtStr}`);
      
      // 验证格式是否正确 (YYYY-MM-DD HH:mm:ss)
      const datePattern = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/;
      if (datePattern.test(createdAtStr) && datePattern.test(updatedAtStr)) {
        logger.info('\n✅ 时间格式正确！');
      } else {
        logger.warn('\n⚠️ 时间格式可能不正确');
      }
    } else {
      logger.warn('未找到作品记录');
    }

  } catch (error: any) {
    logger.error('验证失败:', error);
    if (error instanceof Error) {
      logger.error('错误堆栈:', error.stack);
    }
    process.exit(1);
  } finally {
    await AppDataSource.destroy();
    process.exit(0);
  }
}

verifyWorkTimestamp().catch(console.error);
