import 'temporal-polyfill/full/global';
import {
  BadRequestException,
  Injectable,
  NotFoundException,
} from '@nestjs/common';
import type { SafeUser } from '../auth/types/auth.types.js';
import {
  normalizeOptionalString,
  normalizeRequiredString,
} from '../common/utils/normalize.js';
import { LeadsService } from '../leads/leads.service.js';
import { PrismaService } from '../prisma/prisma.service.js';
import type { CreateActivityDto } from './dto/create-activity.dto.js';
import type { UpdateActivityDto } from './dto/update-activity.dto.js';
import type { ActivityResponse } from './types/activity.types.js';

const ACTIVITY_SELECT = [
  'id',
  'type',
  'title',
  'description',
  'dueAt',
  'completedAt',
  'leadId',
  'userId',
  'createdAt',
  'updatedAt',
] as const;

@Injectable()
export class ActivitiesService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly leadsService: LeadsService,
  ) {}

  async listForLead(
    leadId: string,
    currentUser: SafeUser,
  ): Promise<ActivityResponse[]> {
    await this.leadsService.findOne(leadId, currentUser);

    return this.prisma.db.orm.public.Activity.select(...ACTIVITY_SELECT)
      .where((a) => a.leadId.eq(leadId))
      .orderBy((a) => a.createdAt.desc())
      .all();
  }

  async createForLead(
    leadId: string,
    dto: CreateActivityDto,
    currentUser: SafeUser,
  ): Promise<ActivityResponse> {
    await this.leadsService.findOne(leadId, currentUser);

    const title = normalizeRequiredString(dto.title);
    if (!title) {
      throw new BadRequestException('title is required');
    }

    return this.prisma.db.orm.public.Activity.select(...ACTIVITY_SELECT).create({
      type: dto.type,
      title,
      description: normalizeOptionalString(dto.description),
      dueAt: this.toInstant(dto.dueAt) ?? null,
      completedAt: this.toInstant(dto.completedAt) ?? null,
      leadId,
      userId: currentUser.id,
    });
  }

  async update(
    id: string,
    dto: UpdateActivityDto,
    currentUser: SafeUser,
  ): Promise<ActivityResponse> {
    const existing = await this.prisma.db.orm.public.Activity.select(
      'id',
      'leadId',
    )
      .where((a) => a.id.eq(id))
      .first();

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

    await this.leadsService.findOne(existing.leadId, currentUser);

    const data: {
      type?: ActivityResponse['type'];
      title?: string;
      description?: string | null;
      dueAt?: unknown;
      completedAt?: unknown;
    } = {};

    if (dto.type !== undefined) {
      data.type = dto.type;
    }

    if (dto.title !== undefined) {
      const title = normalizeRequiredString(dto.title);
      if (!title) {
        throw new BadRequestException('title is required');
      }
      data.title = title;
    }

    if (dto.description !== undefined) {
      data.description =
        dto.description === null
          ? null
          : normalizeOptionalString(dto.description);
    }

    if (dto.dueAt !== undefined) {
      data.dueAt = dto.dueAt === null ? null : this.toInstant(dto.dueAt);
    }

    if (dto.completedAt !== undefined) {
      data.completedAt =
        dto.completedAt === null ? null : this.toInstant(dto.completedAt);
    }

    if (Object.keys(data).length === 0) {
      const current = await this.prisma.db.orm.public.Activity.select(
        ...ACTIVITY_SELECT,
      )
        .where((a) => a.id.eq(id))
        .first();
      if (!current) {
        throw new NotFoundException('Activity not found');
      }
      return current;
    }

    const updated = await this.prisma.db.orm.public.Activity.select(
      ...ACTIVITY_SELECT,
    )
      .where((a) => a.id.eq(id))
      .update(data);

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

    return activity;
  }

  private toInstant(value: Date | undefined): unknown {
    if (!value) {
      return undefined;
    }

    const { Temporal: temporalApi } = globalThis as typeof globalThis & {
      Temporal: {
        Instant: { from: (input: string) => unknown };
      };
    };

    return temporalApi.Instant.from(value.toISOString());
  }
}