import { prisma } from '../../lib/prisma'

type DbClient = Pick<typeof prisma, 'company' | 'brandSettings' | 'contractSettings' | 'subscription' | 'employee'>

type CompanySignupInput = {
  companyName: string
  legalName: string
  slug: string
  ownerEmail: string
  companyEmail: string
  companyPhone: string
  streetAddress: string
  city: string
  country: string
  zipCode: string
  legalForm: string
  managerName: string
  iceNumber: string
  taxId: string
  operatingLicenseNumber: string
  operatingLicenseIssuedAt: string
  operatingLicenseIssuedBy: string
  fax?: string
  yearsActive: string
  representativeName?: string
  representativeTitle?: string
  responsibleName: string
  responsibleRole: string
  responsibleIdentityNumber: string
  responsibleQualification?: string
  responsiblePhone: string
  responsibleEmail: string
  currency: 'MAD'
  registrationNumber: string
  plan: 'STARTER' | 'GROWTH' | 'PRO'
  billingPeriod: 'MONTHLY' | 'ANNUAL'
  preferredLanguage: 'en' | 'fr' | 'ar'
  firstName: string
  lastName: string
  passwordHash: string
  now: Date
  trialEndAt: Date
}

export function findCompanyBySlug(slug: string) {
  return prisma.company.findUnique({ where: { slug } })
}

export function findCompanyByEmail(email: string) {
  return prisma.company.findUnique({ where: { email } })
}

export function findEmployeeByEmail(email: string) {
  return prisma.employee.findFirst({ where: { email } })
}

export async function createCompanySignup(db: DbClient, input: CompanySignupInput) {
  const company = await db.company.create({
    data: {
      name: input.companyName,
      slug: input.slug,
      email: input.companyEmail,
      phone: input.companyPhone,
      address: {
        streetAddress: input.streetAddress,
        city: input.city,
        country: input.country,
        zipCode: input.zipCode,
        legalName: input.legalName,
        legalForm: input.legalForm,
        companyEmail: input.companyEmail,
        managerName: input.managerName,
        iceNumber: input.iceNumber,
        operatingLicenseNumber: input.operatingLicenseNumber,
        operatingLicenseIssuedAt: input.operatingLicenseIssuedAt,
        operatingLicenseIssuedBy: input.operatingLicenseIssuedBy,
        fax: input.fax || null,
        yearsActive: input.yearsActive,
        representativeName: input.representativeName || null,
        representativeTitle: input.representativeTitle || null,
        responsibleName: input.responsibleName,
        responsibleRole: input.responsibleRole,
        responsibleIdentityNumber: input.responsibleIdentityNumber,
        responsibleQualification: input.responsibleQualification || null,
        responsiblePhone: input.responsiblePhone,
        responsibleEmail: input.responsibleEmail,
      },
      status: 'TRIALING',
    },
  })

  await db.brandSettings.create({
    data: {
      companyId: company.id,
      displayName: input.companyName,
      subdomain: input.slug,
      publicEmail: input.companyEmail,
      publicPhone: input.companyPhone,
      publicAddress: input.streetAddress,
      publicCity: input.city,
      publicCountry: input.country,
      defaultLocale: input.preferredLanguage,
      defaultCurrency: input.currency,
    },
  })

  await db.contractSettings.create({
    data: {
      companyId: company.id,
      legalName: input.legalName,
      registrationNumber: input.registrationNumber,
      taxId: input.taxId,
    },
  })

  await db.subscription.create({
    data: {
      companyId: company.id,
      plan: input.plan,
      billingPeriod: input.billingPeriod,
      currency: input.currency,
      status: 'TRIALING',
      trialStartAt: input.now,
      trialEndAt: input.trialEndAt,
      currentPeriodStart: input.now,
      currentPeriodEnd: input.trialEndAt,
    },
  })

  const employee = await db.employee.create({
    data: {
      companyId: company.id,
      clerkUserId: `local_owner_${company.id}`,
      firstName: input.firstName,
      lastName: input.lastName,
      email: input.ownerEmail,
      phone: input.companyPhone,
      passwordHash: input.passwordHash,
      emailVerified: input.now,
      role: 'OWNER',
      preferredLanguage: input.preferredLanguage,
      isActive: true,
    },
  })

  return { company, employee }
}
