import { Injectable } from "@nestjs/common";
import { Prisma } from "@prisma/client";
import { PrismaService } from "../prisma/prisma.service";
import type { UpdatePreferencesDto, PreferencesResponseDto } from "./dto";

/**
 * Service for managing user preferences
 */
@Injectable()
export class PreferencesService {
  constructor(private readonly prisma: PrismaService) {}

  /**
   * Get user preferences (create with defaults if not exists)
   */
  async getPreferences(userId: string): Promise<PreferencesResponseDto> {
    let preferences = await this.prisma.userPreference.findUnique({
      where: { userId },
    });

    // Create default preferences if they don't exist
    preferences ??= await this.prisma.userPreference.create({
      data: {
        userId,
        theme: "system",
        locale: "en",
        settings: {} as unknown as Prisma.InputJsonValue,
      },
    });

    return {
      id: preferences.id,
      userId: preferences.userId,
      theme: preferences.theme,
      locale: preferences.locale,
      timezone: preferences.timezone,
      settings: preferences.settings as Record<string, unknown>,
      updatedAt: preferences.updatedAt,
    };
  }

  /**
   * Update user preferences
   */
  async updatePreferences(
    userId: string,
    updateDto: UpdatePreferencesDto
  ): Promise<PreferencesResponseDto> {
    // Check if preferences exist
    const existing = await this.prisma.userPreference.findUnique({
      where: { userId },
    });

    let preferences;

    if (existing) {
      // Update existing preferences
      preferences = await this.prisma.userPreference.update({
        where: { userId },
        data: {
          ...(updateDto.theme && { theme: updateDto.theme }),
          ...(updateDto.locale && { locale: updateDto.locale }),
          ...(updateDto.timezone !== undefined && {
            timezone: updateDto.timezone,
          }),
          ...(updateDto.settings && {
            settings: updateDto.settings as unknown as Prisma.InputJsonValue,
          }),
        },
      });
    } else {
      // Create new preferences
      const createData: Prisma.UserPreferenceUncheckedCreateInput = {
        userId,
        theme: updateDto.theme ?? "system",
        locale: updateDto.locale ?? "en",
        settings: (updateDto.settings ?? {}) as unknown as Prisma.InputJsonValue,
      };

      if (updateDto.timezone !== undefined) {
        createData.timezone = updateDto.timezone;
      }

      preferences = await this.prisma.userPreference.create({
        data: createData,
      });
    }

    return {
      id: preferences.id,
      userId: preferences.userId,
      theme: preferences.theme,
      locale: preferences.locale,
      timezone: preferences.timezone,
      settings: preferences.settings as Record<string, unknown>,
      updatedAt: preferences.updatedAt,
    };
  }
}
