import { prisma } from '../../infra/database/prisma'
import type { UserRole } from '@prisma/client'

export class AuthRepository {
  async findByEmail(email: string) {
    return prisma.user.findUnique({ where: { email } })
  }

  async findById(id: string) {
    return prisma.user.findUnique({
      where: { id },
      select: {
        id: true,
        name: true,
        email: true,
        role: true,
        isActive: true,
        planId: true,
        trialEndsAt: true,
        createdAt: true,
      },
    })
  }

  async create(data: {
    name: string
    email: string
    passwordHash: string
    role?: UserRole
    planId?: string
  }) {
    return prisma.user.create({
      data: {
        name: data.name,
        email: data.email,
        passwordHash: data.passwordHash,
        role: data.role ?? 'USER',
        planId: data.planId,
        trialEndsAt: new Date(Date.now() + 14 * 24 * 60 * 60 * 1000), // 14 dias de trial
      },
      select: {
        id: true,
        name: true,
        email: true,
        role: true,
        planId: true,
        trialEndsAt: true,
        createdAt: true,
      },
    })
  }

  async updatePassword(id: string, passwordHash: string) {
    return prisma.user.update({ where: { id }, data: { passwordHash } })
  }

  async setActive(id: string, isActive: boolean) {
    return prisma.user.update({ where: { id }, data: { isActive } })
  }
}
