import { BadRequestException, 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 { CreateTaskDto } from './dto/create-task.dto';
import { ListTasksQuery } from './dto/list-tasks.query';
import { UpdateTaskDto } from './dto/update-task.dto';

const NOT_FOUND = 'Task not found';

export const taskSelect = {
  id: true,
  title: true,
  description: true,
  type: true,
  priority: true,
  dueDate: true,
  completed: true,
  completedAt: true,
  ownerId: true,
  leadId: true,
  contactId: true,
  accountId: true,
  dealId: true,
  projectId: true,
  milestoneId: 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 } },
  project: { select: { id: true, name: true, projectNumber: true } },
  milestone: { select: { id: true, title: true } },
} satisfies Prisma.TaskSelect;

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

  // Returns paginated tasks and tab counts for open, today, upcoming, overdue, and done.
  async list(ctx: RequestTenantContext, q: ListTasksQuery) {
    const page = Math.max(1, q.page ?? 1);
    const limit = Math.min(100, Math.max(1, q.limit ?? 50));
    const skip = (page - 1) * limit;

    const todayStart = new Date();
    todayStart.setHours(0, 0, 0, 0);
    const todayEnd = new Date(todayStart);
    todayEnd.setDate(todayEnd.getDate() + 1);

    const baseWhere: Prisma.TaskWhereInput = {
      ...(q.priority ? { priority: q.priority } : {}),
      ...(q.ownerId ? { ownerId: q.ownerId } : {}),
      ...(q.leadId ? { leadId: q.leadId } : {}),
      ...(q.contactId ? { contactId: q.contactId } : {}),
      ...(q.accountId ? { accountId: q.accountId } : {}),
      ...(q.dealId ? { dealId: q.dealId } : {}),
      ...(q.projectId ? { projectId: q.projectId } : {}),
      ...(q.q
        ? {
            OR: [{ title: { contains: q.q } }, { description: { contains: q.q } }],
          }
        : {}),
    };

    const [openCount, todayCount, upcomingCount, overdueCount, doneCount] = await Promise.all([
      this.prisma.task.count({
        where: this.tenant.scopeWhere(ctx, {
          ...baseWhere,
          completed: false,
        }),
      }),
      this.prisma.task.count({
        where: this.tenant.scopeWhere(ctx, {
          ...baseWhere,
          completed: false,
          dueDate: { gte: todayStart, lt: todayEnd },
        }),
      }),
      this.prisma.task.count({
        where: this.tenant.scopeWhere(ctx, {
          ...baseWhere,
          completed: false,
          dueDate: { gte: todayEnd },
        }),
      }),
      this.prisma.task.count({
        where: this.tenant.scopeWhere(ctx, {
          ...baseWhere,
          completed: false,
          dueDate: { lt: todayStart },
        }),
      }),
      this.prisma.task.count({
        where: this.tenant.scopeWhere(ctx, {
          ...baseWhere,
          completed: true,
        }),
      }),
    ]);

    const view = q.view ?? 'open';
    const viewCondition: Prisma.TaskWhereInput = {};
    if (view === 'open') {
      viewCondition.completed = false;
    } else if (view === 'today') {
      viewCondition.completed = false;
      viewCondition.dueDate = { gte: todayStart, lt: todayEnd };
    } else if (view === 'upcoming') {
      viewCondition.completed = false;
      viewCondition.dueDate = { gte: todayEnd };
    } else if (view === 'overdue') {
      viewCondition.completed = false;
      viewCondition.dueDate = { lt: todayStart };
    } else if (view === 'done') {
      viewCondition.completed = true;
    }

    const where = this.tenant.scopeWhere(ctx, {
      ...baseWhere,
      ...viewCondition,
    });

    const [items, total] = await Promise.all([
      this.prisma.task.findMany({
        where,
        select: taskSelect,
        orderBy: [{ dueDate: 'asc' }, { id: 'desc' }],
        skip,
        take: limit,
      }),
      this.prisma.task.count({ where }),
    ]);

    return {
      data: items,
      meta: {
        total,
        page,
        limit,
        totalPages: Math.ceil(total / limit) || 1,
      },
      counts: {
        open: openCount,
        today: todayCount,
        upcoming: upcomingCount,
        overdue: overdueCount,
        done: doneCount,
      },
    };
  }

  // Retrieves task details by ID within tenant scope.
  async get(ctx: RequestTenantContext, id: string) {
    const task = await this.prisma.task.findFirst({
      where: this.tenant.scopeWhere(ctx, { id }),
      select: taskSelect,
    });
    if (!task) throw new NotFoundException(NOT_FOUND);
    return task;
  }

  // Creates a new task record within tenant scope.
  async create(ctx: RequestTenantContext, dto: CreateTaskDto) {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    await assertTenantOwner(this.prisma, tenantId, dto.ownerId);
    await this.assertMilestoneInProject(tenantId, dto.projectId, dto.milestoneId);

    try {
      return await this.prisma.task.create({
        data: this.tenant.scopeCreate(ctx, {
          title: dto.title.trim(),
          description: dto.description?.trim() || null,
          type: dto.type ?? 'To-do',
          priority: dto.priority ?? 'Medium',
          dueDate: new Date(dto.dueDate),
          completed: false,
          ownerId: dto.ownerId ?? ctx.userId,
          leadId: dto.leadId ?? null,
          contactId: dto.contactId ?? null,
          accountId: dto.accountId ?? null,
          dealId: dto.dealId ?? null,
          projectId: dto.projectId ?? null,
          milestoneId: dto.milestoneId ?? null,
        }),
        select: taskSelect,
      });
    } catch (err) {
      rethrowRelationConflict(err, 'Linked record does not exist');
    }
  }

  /** Ensures a milestone is only linked together with the project it belongs to. */
  private async assertMilestoneInProject(tenantId: string, projectId: string | null | undefined, milestoneId: string | null | undefined): Promise<void> {
    if (!milestoneId) return;
    if (!projectId) throw new BadRequestException('Choose the project before choosing a milestone');
    const milestone = await this.prisma.milestone.findFirst({ where: { tenantId, id: milestoneId, projectId }, select: { id: true } });
    if (!milestone) throw new BadRequestException('That milestone does not belong to the selected project');
  }

  // Updates an existing task's properties and completion status.
  async update(ctx: RequestTenantContext, id: string, dto: UpdateTaskDto) {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    const existing = await this.get(ctx, id);
    if (dto.projectId !== undefined || dto.milestoneId !== undefined) {
      const projectId = dto.projectId !== undefined ? dto.projectId : existing.projectId;
      const milestoneId = dto.milestoneId !== undefined ? dto.milestoneId : dto.projectId !== undefined ? null : existing.milestoneId;
      await this.assertMilestoneInProject(tenantId, projectId, milestoneId);
    }

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

    const data: Prisma.TaskUncheckedUpdateInput = {};
    if (dto.title !== undefined) data.title = dto.title.trim();
    if (dto.description !== undefined) data.description = dto.description?.trim() || null;
    if (dto.type !== undefined) data.type = dto.type;
    if (dto.priority !== undefined) data.priority = dto.priority;
    if (dto.dueDate !== undefined) data.dueDate = new Date(dto.dueDate);
    if (dto.completed !== undefined) {
      data.completed = dto.completed;
      data.completedAt = dto.completed ? new Date() : 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;
    if (dto.projectId !== undefined) data.projectId = dto.projectId || null;
    if (dto.milestoneId !== undefined) data.milestoneId = dto.milestoneId || null;

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

  // Toggles the completed state of a task and updates completed timestamp.
  async toggle(ctx: RequestTenantContext, id: string) {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    const existing = await this.get(ctx, id);
    const completed = !existing.completed;
    return this.prisma.task.update({
      where: { tenantId_id: { tenantId, id } },
      data: {
        completed,
        completedAt: completed ? new Date() : null,
      },
      select: taskSelect,
    });
  }

  // Deletes a task record within tenant scope.
  async remove(ctx: RequestTenantContext, actor: CrmActor, id: string) {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    assertCanDelete(actor);
    await this.get(ctx, id);
    await this.prisma.task.delete({
      where: { tenantId_id: { tenantId, id } },
    });
    return { success: true };
  }
}
