"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.albumsService = exports.AlbumsService = void 0;
const models_1 = require("../../models");
/**
 * 专辑服务
 */
class AlbumsService {
    /**
     * 获取或创建默认专辑
     */
    async getOrCreateDefaultAlbum() {
        let defaultAlbum = await models_1.prisma.album.findFirst({
            where: { isDefault: true },
        });
        if (!defaultAlbum) {
            defaultAlbum = await models_1.prisma.album.create({
                data: {
                    name: '默认专辑',
                    description: '包含所有未归类音频的默认专辑',
                    isDefault: true,
                },
            });
        }
        return defaultAlbum;
    }
    /**
     * 创建专辑
     */
    async createAlbum(data) {
        return models_1.prisma.album.create({
            data: {
                name: data.name,
                description: data.description,
                coverUrl: data.coverUrl,
                userId: data.userId,
            },
        });
    }
    /**
     * 获取专辑列表
     */
    async getAlbums(options) {
        const { page = 1, pageSize = 20 } = options || {};
        const [albums, total] = await Promise.all([
            models_1.prisma.album.findMany({
                skip: (page - 1) * pageSize,
                take: pageSize,
                orderBy: { createdAt: 'desc' },
                include: {
                    _count: {
                        select: { subscriptions: true, albumAudios: true },
                    },
                },
            }),
            models_1.prisma.album.count(),
        ]);
        // 获取所有未分类的音频数量
        const uncategorizedCount = await models_1.prisma.audio.count({
            where: { albumId: null, status: 'completed' },
        });
        return {
            list: albums.map((album) => {
                // 默认专辑需要加上未分类音频的数量
                const audioCount = album.isDefault
                    ? album._count?.albumAudios + uncategorizedCount
                    : album._count?.albumAudios;
                return {
                    ...album,
                    subscriberCount: album._count?.subscriptions || 0,
                    audioCount: audioCount || 0,
                    _count: undefined,
                };
            }),
            total,
            page,
            pageSize,
            totalPages: Math.ceil(total / pageSize),
        };
    }
    /**
     * 获取专辑详情
     */
    async getAlbumById(albumId) {
        const album = await models_1.prisma.album.findUnique({
            where: { id: albumId },
            include: {
                _count: {
                    select: { subscriptions: true },
                },
            },
        });
        if (!album) {
            throw new Error('专辑不存在');
        }
        return {
            ...album,
            subscriberCount: album._count?.subscriptions || 0,
            _count: undefined,
        };
    }
    /**
     * 更新专辑
     */
    async updateAlbum(albumId, data) {
        return models_1.prisma.album.update({
            where: { id: albumId },
            data: {
                name: data.name,
                description: data.description,
                coverUrl: data.coverUrl,
            },
        });
    }
    /**
     * 删除专辑
     */
    async deleteAlbum(albumId) {
        await models_1.prisma.album.delete({
            where: { id: albumId },
        });
    }
    /**
     * 获取专辑内的音频列表
     */
    async getAlbumAudios(albumId) {
        // 检查是否是默认专辑
        const album = await models_1.prisma.album.findUnique({ where: { id: albumId } });
        const isDefault = album?.isDefault || false;
        // 获取通过 albumId 直接关联的音频
        const directAudios = await models_1.prisma.audio.findMany({
            where: { albumId },
            orderBy: { createdAt: 'desc' },
        });
        // 获取通过 AlbumAudio 中间表关联的音频
        const albumAudios = await models_1.prisma.albumAudio.findMany({
            where: { albumId },
            include: {
                audio: true,
            },
            orderBy: { order: 'asc' },
        });
        // 如果是默认专辑，还需要获取 albumId 为 null 的音频
        let uncategorizedAudios = [];
        if (isDefault) {
            uncategorizedAudios = await models_1.prisma.audio.findMany({
                where: {
                    albumId: null,
                    status: 'completed',
                },
                orderBy: { createdAt: 'desc' },
            });
        }
        // 合并所有音频并去重
        const audioMap = new Map();
        // 先添加直接关联的音频
        directAudios.forEach((audio) => {
            audioMap.set(audio.id, audio);
        });
        // 添加中间表关联的音频
        albumAudios.forEach((aa) => {
            audioMap.set(aa.audio.id, {
                ...aa.audio,
                order: aa.order,
                addedAt: aa.addedAt,
            });
        });
        // 添加未分类音频
        uncategorizedAudios.forEach((audio) => {
            if (!audioMap.has(audio.id)) {
                audioMap.set(audio.id, audio);
            }
        });
        return Array.from(audioMap.values()).sort((a, b) => {
            // 按添加时间排序，如果没有添加时间则按创建时间
            const timeA = a.addedAt || a.createdAt;
            const timeB = b.addedAt || b.createdAt;
            return new Date(timeB).getTime() - new Date(timeA).getTime();
        });
    }
    /**
     * 添加音频到专辑
     */
    async addAudioToAlbum(albumId, audioId, order = 0) {
        // 检查专辑是否存在
        const album = await models_1.prisma.album.findUnique({ where: { id: albumId } });
        if (!album) {
            throw new Error('专辑不存在');
        }
        // 检查音频是否存在
        const audio = await models_1.prisma.audio.findUnique({ where: { id: audioId } });
        if (!audio) {
            throw new Error('音频不存在');
        }
        return models_1.prisma.albumAudio.create({
            data: {
                albumId,
                audioId,
                order,
            },
        });
    }
    /**
     * 从专辑移除音频
     */
    async removeAudioFromAlbum(albumId, audioId) {
        await models_1.prisma.albumAudio.delete({
            where: {
                albumId_audioId: {
                    albumId,
                    audioId,
                },
            },
        });
    }
    /**
     * 调整专辑中音频的顺序
     */
    async reorderAudio(albumId, audioId, order) {
        return models_1.prisma.albumAudio.update({
            where: {
                albumId_audioId: {
                    albumId,
                    audioId,
                },
            },
            data: { order },
        });
    }
    /**
     * 订阅专辑
     */
    async subscribeAlbum(userId, albumId) {
        // 检查专辑是否存在
        const album = await models_1.prisma.album.findUnique({ where: { id: albumId } });
        if (!album) {
            throw new Error('专辑不存在');
        }
        return models_1.prisma.albumSubscription.upsert({
            where: {
                userId_albumId: {
                    userId,
                    albumId,
                },
            },
            update: {},
            create: {
                userId,
                albumId,
            },
        });
    }
    /**
     * 取消订阅专辑
     */
    async unsubscribeAlbum(userId, albumId) {
        await models_1.prisma.albumSubscription.delete({
            where: {
                userId_albumId: {
                    userId,
                    albumId,
                },
            },
        });
    }
    /**
     * 获取用户已订阅的专辑列表
     */
    async getSubscribedAlbums(userId) {
        const subscriptions = await models_1.prisma.albumSubscription.findMany({
            where: { userId },
            include: {
                album: {
                    include: {
                        _count: {
                            select: { subscriptions: true },
                        },
                    },
                },
            },
            orderBy: { createdAt: 'desc' },
        });
        return subscriptions.map((sub) => ({
            ...sub.album,
            subscriberCount: sub.album._count?.subscriptions || 0,
            subscribedAt: sub.createdAt,
            _count: undefined,
        }));
    }
    /**
     * 检查用户是否已订阅专辑
     */
    async isSubscribed(userId, albumId) {
        const subscription = await models_1.prisma.albumSubscription.findUnique({
            where: {
                userId_albumId: {
                    userId,
                    albumId,
                },
            },
        });
        return !!subscription;
    }
}
exports.AlbumsService = AlbumsService;
// 导出单例
exports.albumsService = new AlbumsService();
