import { Injectable ,Logger} from '@nestjs/common';
import { BaseService } from '../base/base.service';

import {
  UserProfile,
  db,
  ObjectType,
  Prisma,
  Resource,
  ResourceStatus,
} from '@nice/common';

@Injectable()
export class ResourceService extends BaseService<Prisma.ResourceDelegate> {
  private readonly logger = new Logger(ResourceService.name);
  constructor() {
    super(db, ObjectType.RESOURCE);
  }
  async create(
    args: Prisma.ResourceCreateArgs,
    params?: { staff?: UserProfile },
  ): Promise<Resource> {
    if (params?.staff) {
      args.data.ownerId = params?.staff?.id;
    }
    return super.create(args);
  }
  async softDeleteByFileId(fileId: string) {
    return this.update({
      where: {
        fileId,
      },
      data: {
        deletedAt: new Date(),
      },
    });
  }
  // 添加保存文件名的方法
  async saveFileName(fileId: string, fileName: string): Promise<void> {
    try {
      this.logger.log(`尝试保存文件名 "${fileName}" 到文件 ${fileId}`);
      
      // 首先检查是否已存在 ShareCode 记录
      const existingShareCode = await db.shareCode.findUnique({
        where: { fileId },
      });
      
      if (existingShareCode) {
        // 如果记录存在，更新文件名
        await db.shareCode.update({
          where: { fileId },
          data: { fileName },
        });
        this.logger.log(`更新了现有记录的文件名 "${fileName}" 到文件 ${fileId}`);
      } else {
        // 如果记录不存在，创建新记录
        await db.shareCode.create({
          data: {
            fileId,
            fileName,
            code: null, // 这里可以设置为 null 或生成一个临时码
            expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000), // 24小时后过期
            isUsed: false,
          },
        });
        this.logger.log(`创建了新记录并保存文件名 "${fileName}" 到文件 ${fileId}`);
      }
    } catch (error) {
      this.logger.error(`保存文件名失败，文件ID: ${fileId}`, error);
      throw error;
    }
  }

  // 添加获取文件名的方法
  async getFileName(fileId: string): Promise<string | null> {
    try {
      const shareCode = await db.shareCode.findUnique({
        where: { fileId },
        select: { fileName: true },
      });
      return shareCode?.fileName || null;
    } catch (error) {
      this.logger.error(`Failed to get filename for ${fileId}`, error);
      return null;
    }
  }
}
