import { ContactList } from "@prisma/client";
import { AppError } from "@/core/errors/app-error";
import { createContactListSchema } from "../dtos/create-contact-list-schema";
import { ContactListsRepository } from "../repositories/contact-lists-repository";

interface CreateContactListUseCaseRequest {
  userId: string;
  body: unknown;
}

interface CreateContactListUseCaseResponse {
  list: ContactList;
}

export class CreateContactListUseCase {
  constructor(private contactListsRepository: ContactListsRepository) {}

  async execute({ userId, body }: CreateContactListUseCaseRequest): Promise<CreateContactListUseCaseResponse> {
    const data = createContactListSchema.parse(body);

    const existing = await this.contactListsRepository.findByUserIdAndName(userId, data.name);
    if (existing) {
      throw AppError.badRequest("Já existe uma lista com esse nome");
    }

    const list = await this.contactListsRepository.create({ ...data, userId });
    return { list };
  }
}
