import { prisma } from '@repo/db';
import type { Resource } from '@repo/db';
import type { DatabaseAdapter, StorageType, ResourceData, CreateResourceData } from '@repo/storage';

// 将 Prisma Resource 转换为 ResourceData 的辅助函数
function transformResource(resource: Resource): ResourceData {
	return {
		id: resource.id,
		fileId: resource.fileId,
		title: resource.title,
		type: resource.type,
		storageType: resource.storageType as StorageType,
		status: resource.status || 'unknown',
		meta: resource.meta,
		createdAt: resource.createdAt,
		updatedAt: resource.updatedAt,
	};
}

export class PrismaDatabaseAdapter implements DatabaseAdapter {
	async getResourceByFileId(fileId: string): Promise<{ status: string; resource?: ResourceData }> {
		const resource = await prisma.resource.findFirst({
			where: { fileId },
		});

		if (!resource) {
			return { status: 'pending' };
		}

		return {
			status: resource.status || 'unknown',
			resource: transformResource(resource),
		};
	}

	async deleteResource(id: string): Promise<ResourceData> {
		const resource = await prisma.resource.delete({
			where: { id },
		});
		return transformResource(resource);
	}

	async deleteFailedUploadingResource(expirationPeriod: number): Promise<{ count: number }> {
		const deletedResources = await prisma.resource.deleteMany({
			where: {
				createdAt: {
					lt: new Date(Date.now() - expirationPeriod),
				},
				status: 'UPLOADING',
			},
		});
		return deletedResources;
	}

	async updateResource(id: string, data: any): Promise<ResourceData> {
		const resource = await prisma.resource.update({
			where: { id },
			data,
		});
		return transformResource(resource);
	}

	async migrateResourcesStorageType(
		fromStorageType: StorageType,
		toStorageType: StorageType,
	): Promise<{ count: number }> {
		const result = await prisma.resource.updateMany({
			where: {
				storageType: fromStorageType,
			},
			data: {
				storageType: toStorageType,
			},
		});

		return { count: result.count };
	}

	async createResource(data: CreateResourceData): Promise<ResourceData> {
		const resource = await prisma.resource.create({
			data: {
				fileId: data.fileId,
				title: data.filename,
				type: data.mimeType ,
				storageType: data.storageType,
				status: data.status || 'UPLOADING',
				meta: {
					size: data.size,
					hash: data.hash,
				},
			},
		});
		return transformResource(resource);
	}

	async updateResourceStatus(fileId: string, status: string, additionalData?: any): Promise<ResourceData> {
		const resource = await prisma.resource.update({
			where: { fileId },
			data: {
				status,
				...additionalData,
			},
		});
		return transformResource(resource);
	}
}
