import { NextRequest } from "next/server";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/lib/auth";
import { UserSettingsService } from "@/lib/services/user-settings.service";
import { ApiResponseHandler } from "@/lib/utils/api-response";
import { AuthenticationError, ValidationError } from "@/lib/errors/app-error";

export async function GET() {
  try {
    const session = await getServerSession(authOptions);

    if (!session?.user?.id) {
      throw new AuthenticationError();
    }

    // 获取或创建用户设置
    const settings = await UserSettingsService.getOrCreateUserSettings(
      session.user.id
    );

    return ApiResponseHandler.success(settings);
  } catch (error) {
    return ApiResponseHandler.error(error as Error);
  }
}

export async function PUT(request: NextRequest) {
  try {
    const session = await getServerSession(authOptions);

    if (!session?.user?.id) {
      throw new AuthenticationError();
    }

    const { defaultQuality, publicProfile, allowDownload } =
      await request.json();

    // 验证音频质量
    if (
      defaultQuality &&
      !["low", "medium", "high", "lossless"].includes(defaultQuality)
    ) {
      throw new ValidationError("无效的音频质量设置");
    }

    // 更新用户设置
    const settings = await UserSettingsService.updateUserSettings(
      session.user.id,
      {
        defaultQuality,
        publicProfile:
          typeof publicProfile === "boolean" ? publicProfile : undefined,
        allowDownload:
          typeof allowDownload === "boolean" ? allowDownload : undefined,
      }
    );

    return ApiResponseHandler.success(settings);
  } catch (error) {
    return ApiResponseHandler.error(error as Error);
  }
}

export async function DELETE() {
  try {
    const session = await getServerSession(authOptions);

    if (!session?.user?.id) {
      throw new AuthenticationError();
    }

    // 重置用户设置为默认值
    const settings = await UserSettingsService.resetUserSettings(
      session.user.id
    );

    return ApiResponseHandler.success(settings);
  } catch (error) {
    return ApiResponseHandler.error(error as Error);
  }
}
