import {
  BadRequestException,
  ConflictException,
  Injectable,
  NotFoundException,
} from '@nestjs/common';
import { or } from '@prisma/orm-postgres/orm-client';
import {
  domainToCompanyName,
  domainToWebsite,
  extractBusinessEmailDomain,
  normalizeDomain,
} from '../common/utils/company-domain.js';
import {
  normalizeOptionalEmail,
  normalizeOptionalString,
  normalizeRequiredString,
} from '../common/utils/normalize.js';
import { PrismaService } from '../prisma/prisma.service.js';
import type { CreateCompanyDto } from './dto/create-company.dto.js';
import type { ListCompaniesQueryDto } from './dto/list-companies-query.dto.js';
import type { UpdateCompanyDto } from './dto/update-company.dto.js';
import type {
  CompanyResponse,
  PaginatedCompaniesResponse,
} from './types/company.types.js';

export const COMPANY_SELECT = [
  'id',
  'name',
  'domain',
  'website',
  'industry',
  'phone',
  'email',
  'address',
  'createdAt',
  'updatedAt',
] as const;

@Injectable()
export class CompaniesService {
  constructor(private readonly prisma: PrismaService) {}

  async create(dto: CreateCompanyDto): Promise<CompanyResponse> {
    const name = normalizeRequiredString(dto.name);
    if (!name) {
      throw new BadRequestException('name is required');
    }

    const domain = dto.domain ? normalizeDomain(dto.domain) : null;
    if (dto.domain && !domain) {
      throw new BadRequestException('Invalid company domain');
    }

    if (domain) {
      const existing = await this.findByDomain(domain);
      if (existing) {
        throw new ConflictException('Company domain already exists');
      }
    }

    try {
      return await this.prisma.db.orm.public.Company.select(
        ...COMPANY_SELECT,
      ).create({
        name,
        domain,
        website: normalizeOptionalString(dto.website),
        industry: normalizeOptionalString(dto.industry),
        phone: normalizeOptionalString(dto.phone),
        email: normalizeOptionalEmail(dto.email),
        address: normalizeOptionalString(dto.address),
      });
    } catch (error) {
      if (domain && this.isUniqueViolation(error)) {
        throw new ConflictException('Company domain already exists');
      }
      throw error;
    }
  }

  /**
   * Resolves a company from a lead email when companyId was not supplied.
   * Creates a company from the business domain when missing.
   * Concurrent creates for the same domain re-read the unique row.
   */
  async resolveCompanyIdFromEmail(
    email: string | null | undefined,
  ): Promise<string | null> {
    const domain = extractBusinessEmailDomain(email);
    if (!domain) {
      return null;
    }

    const company = await this.findOrCreateByDomain(domain);
    return company.id;
  }

  async findOrCreateByDomain(domainInput: string): Promise<CompanyResponse> {
    const domain = normalizeDomain(domainInput);
    if (!domain) {
      throw new BadRequestException('Invalid company domain');
    }

    const existing = await this.findByDomain(domain);
    if (existing) {
      return existing;
    }

    try {
      return await this.prisma.db.orm.public.Company.select(
        ...COMPANY_SELECT,
      ).create({
        name: domainToCompanyName(domain),
        domain,
        website: domainToWebsite(domain),
        industry: null,
        phone: null,
        email: null,
        address: null,
      });
    } catch (error) {
      if (this.isUniqueViolation(error)) {
        const raced = await this.findByDomain(domain);
        if (raced) {
          return raced;
        }
      }
      throw error;
    }
  }

  async findByDomain(domain: string): Promise<CompanyResponse | null> {
    const normalized = normalizeDomain(domain);
    if (!normalized) {
      return null;
    }

    return this.prisma.db.orm.public.Company.select(...COMPANY_SELECT)
      .where((c) => c.domain.eq(normalized))
      .first();
  }

  async findAll(
    query: ListCompaniesQueryDto,
  ): Promise<PaginatedCompaniesResponse> {
    const page = query.page ?? 1;
    const limit = query.limit ?? 20;
    const offset = (page - 1) * limit;
    const search = query.search?.trim();
    const pattern = search
      ? `%${this.escapeIlikePattern(search)}%`
      : undefined;

    const totalResult = await (
      pattern
        ? this.prisma.db.orm.public.Company.where((c) =>
            or(
              c.name.ilike(pattern),
              c.domain.ilike(pattern),
              c.industry.ilike(pattern),
              c.email.ilike(pattern),
              c.website.ilike(pattern),
            ),
          )
        : this.prisma.db.orm.public.Company
    ).aggregate((agg) => ({ total: agg.count() }));

    const filtered = pattern
      ? this.prisma.db.orm.public.Company.select(...COMPANY_SELECT).where((c) =>
          or(
            c.name.ilike(pattern),
            c.domain.ilike(pattern),
            c.industry.ilike(pattern),
            c.email.ilike(pattern),
            c.website.ilike(pattern),
          ),
        )
      : this.prisma.db.orm.public.Company.select(...COMPANY_SELECT);

    const data = await filtered
      .orderBy((c) => c.name.asc())
      .limit(limit)
      .offset(offset)
      .all();

    const total = totalResult.total;

    return {
      data,
      meta: {
        total,
        page,
        limit,
        totalPages: total === 0 ? 0 : Math.ceil(total / limit),
      },
    };
  }

  async findOne(id: string): Promise<CompanyResponse> {
    const company = await this.prisma.db.orm.public.Company.select(
      ...COMPANY_SELECT,
    )
      .where((c) => c.id.eq(id))
      .first();

    if (!company) {
      throw new NotFoundException('Company not found');
    }

    return company;
  }

  async update(id: string, dto: UpdateCompanyDto): Promise<CompanyResponse> {
    await this.ensureCompanyExists(id);

    const data: {
      name?: string;
      domain?: string | null;
      website?: string | null;
      industry?: string | null;
      phone?: string | null;
      email?: string | null;
      address?: string | null;
    } = {};

    if (dto.name !== undefined) {
      const name = normalizeRequiredString(dto.name);
      if (!name) {
        throw new BadRequestException('name cannot be empty');
      }
      data.name = name;
    }
    if (dto.domain !== undefined) {
      if (dto.domain === null || dto.domain === '') {
        data.domain = null;
      } else {
        const domain = normalizeDomain(dto.domain);
        if (!domain) {
          throw new BadRequestException('Invalid company domain');
        }
        data.domain = domain;
      }
    }
    if (dto.website !== undefined) {
      data.website = normalizeOptionalString(dto.website);
    }
    if (dto.industry !== undefined) {
      data.industry = normalizeOptionalString(dto.industry);
    }
    if (dto.phone !== undefined) {
      data.phone = normalizeOptionalString(dto.phone);
    }
    if (dto.email !== undefined) {
      data.email = normalizeOptionalEmail(dto.email);
    }
    if (dto.address !== undefined) {
      data.address = normalizeOptionalString(dto.address);
    }

    if (Object.keys(data).length === 0) {
      return this.findOne(id);
    }

    try {
      const updated = await this.prisma.db.orm.public.Company.select(
        ...COMPANY_SELECT,
      )
        .where((c) => c.id.eq(id))
        .update(data);

      const company = Array.isArray(updated) ? updated[0] : updated;
      if (!company) {
        throw new NotFoundException('Company not found');
      }

      return company;
    } catch (error) {
      if (this.isUniqueViolation(error)) {
        throw new ConflictException('Company domain already exists');
      }
      throw error;
    }
  }

  async remove(id: string): Promise<void> {
    await this.ensureCompanyExists(id);

    const leadCount = await this.prisma.db.orm.public.Lead.where((l) =>
      l.companyId.eq(id),
    ).aggregate((agg) => ({ total: agg.count() }));

    if (leadCount.total > 0) {
      throw new ConflictException(
        'Company has associated leads and cannot be deleted',
      );
    }

    await this.prisma.db.orm.public.Company.where((c) => c.id.eq(id)).delete();
  }

  private async ensureCompanyExists(id: string): Promise<void> {
    const existing = await this.prisma.db.orm.public.Company.select('id')
      .where((c) => c.id.eq(id))
      .first();

    if (!existing) {
      throw new NotFoundException('Company not found');
    }
  }

  private isUniqueViolation(error: unknown): boolean {
    if (!error || typeof error !== 'object') {
      return false;
    }

    const candidate = error as {
      code?: string;
      cause?: { code?: string };
      message?: string;
    };

    if (candidate.code === '23505' || candidate.cause?.code === '23505') {
      return true;
    }

    return (
      typeof candidate.message === 'string' &&
      /unique|duplicate key/i.test(candidate.message)
    );
  }

  private escapeIlikePattern(value: string): string {
    return value.replace(/[\\%_]/g, '\\$&');
  }
}
