import { GenericCrudService } from '@/server/utils/generic-crud.service';
import { DataSource } from 'typeorm';
import { VodVideo } from './vod-video.entity';

export class VodVideoService extends GenericCrudService<VodVideo> {
  constructor(dataSource: DataSource) {
    super(dataSource, VodVideo);
  }

  /**
   * 重写获取列表方法，添加默认过滤条件
   */
  async getList(
    page: number = 1,
    pageSize: number = 10,
    keyword?: string,
    searchFields?: string[],
    where: Partial<VodVideo> = {},
    relations: string[] = [],
    order: { [P in keyof VodVideo]?: 'ASC' | 'DESC' } = {},
    filters?: any
  ): Promise<[VodVideo[], number]> {
    // 可以在这里添加自定义的业务逻辑
    // 例如：默认按创建时间倒序排序
    if (Object.keys(order).length === 0) {
      order.createdAt = 'DESC';
    }

    return super.getList(page, pageSize, keyword, searchFields, where, relations, order, filters);
  }

  /**
   * 根据状态获取视频列表
   */
  async getVideosByStatus(status: number, page: number = 1, pageSize: number = 10): Promise<[VodVideo[], number]> {
    return this.getList(page, pageSize, undefined, undefined, { status });
  }

  /**
   * 获取处理中的视频
   */
  async getProcessingVideos(page: number = 1, pageSize: number = 10): Promise<[VodVideo[], number]> {
    return this.getVideosByStatus(1, page, pageSize);
  }

  /**
   * 获取已完成的视频
   */
  async getCompletedVideos(page: number = 1, pageSize: number = 10): Promise<[VodVideo[], number]> {
    return this.getVideosByStatus(2, page, pageSize);
  }

  /**
   * 更新视频状态
   */
  async updateVideoStatus(id: number, status: number, userId?: number): Promise<VodVideo | null> {
    return this.update(id, { status }, userId);
  }

  /**
   * 更新视频处理信息（状态、时长、大小等）
   */
  async updateVideoProcessingInfo(
    id: number, 
    status: number, 
    duration?: number, 
    size?: number,
    videoUrl?: string,
    coverUrl?: string,
    userId?: number
  ): Promise<VodVideo | null> {
    const updateData: any = { status };
    
    if (duration !== undefined) updateData.duration = duration;
    if (size !== undefined) updateData.size = size;
    if (videoUrl !== undefined) updateData.videoUrl = videoUrl;
    if (coverUrl !== undefined) updateData.coverUrl = coverUrl;

    return this.update(id, updateData, userId);
  }
}