import { Injectable, NotFoundException } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../../prisma/prisma.service';
import { RequestTenantContext, TenantQueryHelper } from '../../common/tenancy/tenant-query.helper';
import { assertCanDelete, assertTenantOwner, rethrowRelationConflict, type CrmActor } from '../../common/crm/crm-record.helper';
import { CreateCalendarEventDto } from './dto/create-calendar-event.dto';
import { ListCalendarEventsQuery } from './dto/list-calendar-events.query';
import { UpdateCalendarEventDto } from './dto/update-calendar-event.dto';

const NOT_FOUND = 'Calendar event not found';

export const calendarEventSelect = {
  id: true,
  title: true,
  type: true,
  date: true,
  startTime: true,
  durationMinutes: true,
  withWhom: true,
  description: true,
  ownerId: true,
  leadId: true,
  contactId: true,
  accountId: true,
  dealId: true,
  createdAt: true,
  updatedAt: true,
  owner: { select: { id: true, name: true, email: true } },
  lead: { select: { id: true, name: true, company: true } },
  contact: { select: { id: true, name: true, email: true } },
  account: { select: { id: true, name: true } },
  deal: { select: { id: true, title: true, dealNumber: true } },
} satisfies Prisma.CalendarEventSelect;

@Injectable()
export class CalendarService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly tenant: TenantQueryHelper,
  ) {}

  // Retrieves calendar events within a date range alongside upcoming scheduled meetings.
  async list(ctx: RequestTenantContext, q: ListCalendarEventsQuery) {
    const now = new Date();
    const year = q.year ?? now.getFullYear();
    const month = q.month ?? now.getMonth();

    let startDate: Date;
    let endDate: Date;

    if (q.from && q.to) {
      startDate = new Date(q.from);
      endDate = new Date(q.to);
    } else {
      startDate = new Date(year, month - 1, 20);
      endDate = new Date(year, month + 1, 15);
    }

    const where: Prisma.CalendarEventWhereInput = this.tenant.scopeWhere(ctx, {
      date: { gte: startDate, lte: endDate },
      ...(q.type ? { type: q.type } : {}),
      ...(q.ownerId ? { ownerId: q.ownerId } : {}),
    });

    const todayStart = new Date();
    todayStart.setHours(0, 0, 0, 0);

    const [events, upcoming] = await Promise.all([
      this.prisma.calendarEvent.findMany({
        where,
        select: calendarEventSelect,
        orderBy: [{ date: 'asc' }, { startTime: 'asc' }],
      }),
      this.prisma.calendarEvent.findMany({
        where: this.tenant.scopeWhere(ctx, {
          date: { gte: todayStart },
        }),
        select: calendarEventSelect,
        orderBy: [{ date: 'asc' }, { startTime: 'asc' }],
        take: 6,
      }),
    ]);

    return {
      data: events,
      upcoming,
      month,
      year,
    };
  }

  // Retrieves a single calendar event by ID scoped to the authenticated tenant.
  async get(ctx: RequestTenantContext, id: string) {
    const ev = await this.prisma.calendarEvent.findFirst({
      where: this.tenant.scopeWhere(ctx, { id }),
      select: calendarEventSelect,
    });
    if (!ev) throw new NotFoundException(NOT_FOUND);
    return ev;
  }

  // Creates a new calendar event linked to an owner and optional CRM entity.
  async create(ctx: RequestTenantContext, dto: CreateCalendarEventDto) {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    await assertTenantOwner(this.prisma, tenantId, dto.ownerId);

    try {
      return await this.prisma.calendarEvent.create({
        data: this.tenant.scopeCreate(ctx, {
          title: dto.title.trim(),
          type: dto.type ?? 'Meeting',
          date: new Date(dto.date),
          startTime: dto.startTime,
          durationMinutes: dto.durationMinutes ?? 30,
          withWhom: dto.withWhom?.trim() || null,
          description: dto.description?.trim() || null,
          ownerId: dto.ownerId ?? ctx.userId,
          leadId: dto.leadId ?? null,
          contactId: dto.contactId ?? null,
          accountId: dto.accountId ?? null,
          dealId: dto.dealId ?? null,
        }),
        select: calendarEventSelect,
      });
    } catch (err) {
      rethrowRelationConflict(err, 'Linked record does not exist');
    }
  }

  // Updates an existing calendar event within tenant boundary.
  async update(ctx: RequestTenantContext, id: string, dto: UpdateCalendarEventDto) {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    await this.get(ctx, id);

    if (dto.ownerId !== undefined) {
      await assertTenantOwner(this.prisma, tenantId, dto.ownerId);
    }

    const data: Prisma.CalendarEventUncheckedUpdateInput = {};
    if (dto.title !== undefined) data.title = dto.title.trim();
    if (dto.type !== undefined) data.type = dto.type;
    if (dto.date !== undefined) data.date = new Date(dto.date);
    if (dto.startTime !== undefined) data.startTime = dto.startTime;
    if (dto.durationMinutes !== undefined) data.durationMinutes = dto.durationMinutes;
    if (dto.withWhom !== undefined) data.withWhom = dto.withWhom?.trim() || null;
    if (dto.description !== undefined) data.description = dto.description?.trim() || null;
    if (dto.ownerId !== undefined) data.ownerId = dto.ownerId || null;
    if (dto.leadId !== undefined) data.leadId = dto.leadId || null;
    if (dto.contactId !== undefined) data.contactId = dto.contactId || null;
    if (dto.accountId !== undefined) data.accountId = dto.accountId || null;
    if (dto.dealId !== undefined) data.dealId = dto.dealId || null;

    try {
      return await this.prisma.calendarEvent.update({
        where: { tenantId_id: { tenantId, id } },
        data,
        select: calendarEventSelect,
      });
    } catch (err) {
      rethrowRelationConflict(err, 'Linked record does not exist');
    }
  }

  // Deletes a calendar event verifying tenant ownership and delete permissions.
  async remove(ctx: RequestTenantContext, actor: CrmActor, id: string) {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    assertCanDelete(actor);
    await this.get(ctx, id);
    await this.prisma.calendarEvent.delete({
      where: { tenantId_id: { tenantId, id } },
    });
    return { success: true };
  }
}
