import { BadRequestException, ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import { DealStage, Prisma, UserStatus } from '@prisma/client';
import { PrismaService } from '../../prisma/prisma.service';
import { RequestTenantContext, TenantQueryHelper } from '../../common/tenancy/tenant-query.helper';
import { assertCanDelete, assertTenantOwner, type CrmActor } from '../../common/crm/crm-record.helper';
import { AddProjectMemberDto } from './dto/add-project-member.dto';
import { CreateMilestoneDto } from './dto/create-milestone.dto';
import { CreateProjectDto } from './dto/create-project.dto';
import { ListProjectsQuery } from './dto/list-projects.query';
import { UpdateMilestoneDto } from './dto/update-milestone.dto';
import { UpdateProjectDto } from './dto/update-project.dto';
import { NumberingService } from '../numbering/numbering.service';

const OPEN_STATUSES = ['Planned', 'Active', 'On hold'];
const isOpen = (status: string) => OPEN_STATUSES.includes(status);

/** Rejects a target end date that falls before the start date. */
function assertDateOrder(startDate: Date, targetEndDate: Date): void {
  if (targetEndDate < startDate) throw new BadRequestException('Target end date must be on or after the start date');
}

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

  /** Ensures every listed user is an active member of the tenant. */
  private async assertActiveUsers(tenantId: string, userIds: string[]): Promise<void> {
    if (!userIds.length) return;
    const found = await this.prisma.user.count({ where: { tenantId, id: { in: userIds }, status: UserStatus.ACTIVE } });
    if (found !== userIds.length) throw new BadRequestException('Choose team members from your organization');
  }

  // Returns paginated projects with health status, budget tracking, and weekly hours.
  async list(t: RequestTenantContext, q: ListProjectsQuery) {
    const tenantId = this.tenant.getRequiredTenantId(t);
    const page = Math.max(1, q.page ?? 1);
    const limit = Math.min(100, Math.max(1, q.limit ?? 20));
    const skip = (page - 1) * limit;

    const filters: Prisma.ProjectWhereInput[] = [];
    if (q.view === 'active') filters.push({ status: { in: OPEN_STATUSES } });
    if (q.view === 'mine') filters.push({ OR: [{ ownerId: t.userId }, { members: { some: { userId: t.userId } } }] });
    if (q.view === 'at_risk') filters.push({ status: { in: OPEN_STATUSES }, targetEndDate: { lt: new Date() } });
    if (q.view === 'completed') filters.push({ status: 'Completed' });
    if (q.status) filters.push({ status: q.status });
    if (q.ownerId) filters.push({ ownerId: q.ownerId });
    if (q.accountId) filters.push({ accountId: q.accountId });
    if (q.targetFrom || q.targetTo) filters.push({ targetEndDate: { ...(q.targetFrom ? { gte: new Date(q.targetFrom) } : {}), ...(q.targetTo ? { lte: new Date(q.targetTo) } : {}) } });
    const term = q.q?.trim();
    if (term) filters.push({ OR: [{ name: { contains: term } }, { projectNumber: { contains: term } }, { account: { name: { contains: term } } }] });
    const where: Prisma.ProjectWhereInput = { tenantId, AND: filters };

    const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
    const [total, projects, activeProjects, atRiskProjects, completedProjects, allWeekEntries] = await Promise.all([
      this.prisma.project.count({ where }),
      this.prisma.project.findMany({
        where,
        skip,
        take: limit,
        orderBy: [{ status: 'asc' }, { targetEndDate: 'asc' }],
        include: {
          account: { select: { id: true, name: true, city: true } },
          deal: { select: { id: true, title: true, dealNumber: true, amount: true } },
          owner: { select: { id: true, name: true, email: true } },
          members: {
            include: { user: { select: { id: true, name: true, email: true } } },
          },
          milestones: { select: { isDone: true } },
          _count: {
            select: {
              tasks: true,
              milestones: true,
              timeEntries: true,
            },
          },
        },
      }),
      this.prisma.project.count({
        where: { tenantId, status: { in: OPEN_STATUSES } },
      }),
      this.prisma.project.count({
        where: {
          tenantId,
          status: { in: OPEN_STATUSES },
          targetEndDate: { lt: new Date() },
        },
      }),
      this.prisma.project.count({
        where: { tenantId, status: 'Completed' },
      }),
      this.prisma.timeEntry.findMany({
        where: { tenantId, date: { gte: sevenDaysAgo } },
        select: { hours: true, isBillable: true },
      }),
    ]);

    const teamHoursThisWeek = allWeekEntries.reduce((s, e) => s + Number(e.hours), 0);
    const billableHoursThisWeek = allWeekEntries.filter((e) => e.isBillable).reduce((s, e) => s + Number(e.hours), 0);
    const billablePercentThisWeek = teamHoursThisWeek > 0 ? Math.round((billableHoursThisWeek / teamHoursThisWeek) * 100) : 0;

    const hourRows = projects.length ? await this.prisma.timeEntry.groupBy({ by: ['projectId', 'isBillable'], where: { tenantId, projectId: { in: projects.map((p) => p.id) } }, _sum: { hours: true } }) : [];
    const hoursFor = (projectId: string, billableOnly: boolean) => hourRows.filter((r) => r.projectId === projectId && (!billableOnly || r.isBillable)).reduce((sum, r) => sum + Number(r._sum.hours ?? 0), 0);

    const items = projects.map((p) => {
      const loggedHours = hoursFor(p.id, false);
      const billableHours = hoursFor(p.id, true);
      const doneMilestones = p.milestones.filter((m) => m.isDone).length;
      const budgetHours = Number(p.budgetHours);
      const isOverBudget = budgetHours > 0 && loggedHours > budgetHours;
      const isPastTarget = isOpen(p.status) && new Date(p.targetEndDate) < new Date();

      return {
        ...p,
        loggedHours,
        billableHours,
        doneMilestones,
        totalMilestones: p.milestones.length,
        isAtRisk: isOverBudget || isPastTarget,
      };
    });

    return {
      data: items,
      meta: {
        total,
        page,
        limit,
        totalPages: Math.ceil(total / limit),
        stats: {
          activeProjects,
          atRiskProjects,
          completedProjects,
          totalProjects: total,
          teamHoursThisWeek,
          billablePercentThisWeek,
        },
      },
    };
  }

  // Retrieves project details with team members, milestones, tasks, and timesheets.
  async get(t: RequestTenantContext, id: string) {
    const tenantId = this.tenant.getRequiredTenantId(t);
    const project = await this.prisma.project.findFirst({
      where: { id, tenantId },
      include: {
        account: true,
        deal: true,
        owner: { select: { id: true, name: true, email: true } },
        members: {
          include: { user: { select: { id: true, name: true, email: true } } },
          orderBy: { joinedAt: 'asc' },
        },
        milestones: {
          orderBy: [{ orderIndex: 'asc' }, { dueDate: 'asc' }],
          include: {
            tasks: {
              select: { id: true, title: true, completed: true },
            },
          },
        },
        tasks: {
          orderBy: [{ completed: 'asc' }, { dueDate: 'asc' }],
          include: {
            owner: { select: { id: true, name: true } },
            milestone: { select: { id: true, title: true } },
          },
        },
        timeEntries: {
          orderBy: { date: 'desc' },
          take: 20,
          include: {
            user: { select: { id: true, name: true } },
            task: { select: { id: true, title: true } },
            milestone: { select: { id: true, title: true } },
          },
        },
        activities: {
          orderBy: { performedAt: 'desc' },
          take: 20,
          include: {
            owner: { select: { id: true, name: true } },
          },
        },
      },
    });

    if (!project) {
      throw new NotFoundException('Project not found');
    }

    const allTimes = await this.prisma.timeEntry.findMany({
      where: { projectId: id, tenantId },
      select: { hours: true, isBillable: true, userId: true },
    });

    const loggedHours = allTimes.reduce((acc, cur) => acc + Number(cur.hours), 0);
    const billableHours = allTimes.filter((te) => te.isBillable).reduce((acc, cur) => acc + Number(cur.hours), 0);
    const budgetHours = Number(project.budgetHours);
    const leftHours = budgetHours - loggedHours;
    const isOverBudget = budgetHours > 0 && leftHours < 0;

    const userHoursMap = new Map<string, number>();
    for (const te of allTimes) {
      userHoursMap.set(te.userId, (userHoursMap.get(te.userId) || 0) + Number(te.hours));
    }

    const membersWithHours = project.members.map((m) => ({
      ...m,
      loggedHours: userHoursMap.get(m.userId) || 0,
    }));

    return {
      ...project,
      members: membersWithHours,
      loggedHours,
      billableHours,
      leftHours,
      isOverBudget,
      isAtRisk: isOverBudget || (isOpen(project.status) && new Date(project.targetEndDate) < new Date()),
    };
  }

  // Creates a new project and initializes membership with the project owner.
  async create(t: RequestTenantContext, dto: CreateProjectDto) {
    const tenantId = this.tenant.getRequiredTenantId(t);
    let accountId = dto.accountId;
    let budgetAmount = dto.budgetAmount || 0;
    let budgetHours = dto.budgetHours || 0;

    if (dto.dealId) {
      const deal = await this.prisma.deal.findFirst({
        where: { id: dto.dealId, tenantId },
      });
      if (!deal) {
        throw new NotFoundException('Selected deal not found');
      }
      if (deal.stage !== DealStage.CLOSED_WON) {
        throw new BadRequestException('Only a won deal can start a project. Mark the deal as won first.');
      }
      if (accountId && deal.accountId && accountId !== deal.accountId) {
        throw new BadRequestException('The deal belongs to a different customer. Pick the deal’s customer.');
      }
      accountId = accountId || deal.accountId || undefined;
      if (!dto.budgetAmount && deal.amount) {
        budgetAmount = Number(deal.amount);
      }
      if (!dto.budgetHours && deal.estimatedHours) {
        budgetHours = deal.estimatedHours;
      }
    }

    if (!accountId) {
      throw new BadRequestException('Select a customer for this project');
    }

    const account = await this.prisma.customer.findFirst({
      where: { id: accountId, tenantId },
    });
    if (!account) {
      throw new NotFoundException('Customer not found');
    }

    const ownerId = dto.ownerId || t.userId;
    await assertTenantOwner(this.prisma, tenantId, ownerId);
    const teamMemberIds = [...new Set((dto.teamMemberIds || []).filter((uid) => uid && uid !== ownerId))];
    await this.assertActiveUsers(tenantId, teamMemberIds);
    const startDate = dto.startDate ? new Date(dto.startDate) : new Date();
    const targetEndDate = dto.targetEndDate ? new Date(dto.targetEndDate) : new Date(startDate.getTime() + 30 * 24 * 60 * 60 * 1000);
    assertDateOrder(startDate, targetEndDate);

    const projectNumber = await this.numbering.getNextNumber(tenantId, 'PROJECT');

    const project = await this.prisma.project.create({
      data: {
        tenantId,
        projectNumber,
        name: dto.name,
        description: dto.description,
        status: dto.status || 'Planned',
        startDate,
        targetEndDate,
        completedAt: dto.status === 'Completed' ? new Date() : null,
        budgetType: dto.budgetType || 'Hours',
        budgetHours,
        budgetAmount,
        accountId,
        dealId: dto.dealId || null,
        ownerId,
        members: {
          create: [
            {
              userId: ownerId,
              roleLabel: 'Project manager',
            },
            ...teamMemberIds.map((userId) => ({
              userId,
              roleLabel: 'Team member',
            })),
          ],
        },
      },
      include: {
        account: true,
        deal: true,
        owner: { select: { id: true, name: true, email: true } },
      },
    });

    return project;
  }

  // Updates project properties and sets completion date if completed.
  async update(t: RequestTenantContext, id: string, dto: UpdateProjectDto) {
    const tenantId = this.tenant.getRequiredTenantId(t);
    const existing = await this.prisma.project.findFirst({
      where: { id, tenantId },
    });
    if (!existing) {
      throw new NotFoundException('Project not found');
    }

    const data: Prisma.ProjectUpdateInput = {};

    const startDate = dto.startDate !== undefined ? new Date(dto.startDate) : existing.startDate;
    const targetEndDate = dto.targetEndDate !== undefined ? new Date(dto.targetEndDate) : existing.targetEndDate;
    assertDateOrder(startDate, targetEndDate);

    if (dto.name !== undefined) data.name = dto.name;
    if (dto.description !== undefined) data.description = dto.description;
    if (dto.startDate !== undefined) data.startDate = startDate;
    if (dto.targetEndDate !== undefined) data.targetEndDate = targetEndDate;
    if (dto.budgetType !== undefined) data.budgetType = dto.budgetType;
    if (dto.budgetHours !== undefined) data.budgetHours = dto.budgetHours;
    if (dto.budgetAmount !== undefined) data.budgetAmount = dto.budgetAmount;
    if (dto.ownerId !== undefined) {
      await assertTenantOwner(this.prisma, tenantId, dto.ownerId);
      data.owner = {
        connect: {
          tenantId_id: { tenantId, id: dto.ownerId },
        },
      };
    }

    if (dto.status !== undefined) {
      data.status = dto.status;
      if (dto.status === 'Completed') {
        data.completedAt = dto.completedAt ? new Date(dto.completedAt) : new Date();
      } else {
        data.completedAt = null;
      }
    }

    return this.prisma.$transaction(async (tx) => {
      if (dto.ownerId !== undefined && dto.ownerId !== existing.ownerId) {
        await tx.projectMember.upsert({
          where: { tenantId_projectId_userId: { tenantId, projectId: id, userId: dto.ownerId } },
          create: { tenantId, projectId: id, userId: dto.ownerId, roleLabel: 'Project manager' },
          update: { roleLabel: 'Project manager' },
        });
      }
      return tx.project.update({
        where: { tenantId_id: { tenantId, id } },
        data,
        include: {
          account: true,
          deal: true,
          owner: { select: { id: true, name: true, email: true } },
        },
      });
    });
  }

  /** Counts the logged time and invoices that would be lost if the project were deleted. */
  async deleteCheck(t: RequestTenantContext, id: string) {
    const tenantId = this.tenant.getRequiredTenantId(t);
    const existing = await this.prisma.project.findFirst({ where: { id, tenantId }, select: { id: true } });
    if (!existing) throw new NotFoundException('Project not found');
    const [timeEntries, invoices, milestones, tasks, files] = await Promise.all([this.prisma.timeEntry.count({ where: { tenantId, projectId: id } }), this.prisma.invoice.count({ where: { tenantId, projectId: id } }), this.prisma.milestone.count({ where: { tenantId, projectId: id } }), this.prisma.task.count({ where: { tenantId, projectId: id } }), this.prisma.file.count({ where: { tenantId, projectId: id } })]);
    const blockers = { timeEntries, invoices };
    return { canDelete: timeEntries === 0 && invoices === 0, blockers, willDelete: { milestones, tasks, files } };
  }

  /** Deletes a project with its milestones, tasks and files; refuses when time is logged or invoices exist. */
  async remove(t: RequestTenantContext, actor: CrmActor, id: string) {
    assertCanDelete(actor);
    const tenantId = this.tenant.getRequiredTenantId(t);
    const check = await this.deleteCheck(t, id);
    if (!check.canDelete) {
      const parts = [check.blockers.timeEntries && `${check.blockers.timeEntries} time ${check.blockers.timeEntries === 1 ? 'entry' : 'entries'}`, check.blockers.invoices && `${check.blockers.invoices} ${check.blockers.invoices === 1 ? 'invoice' : 'invoices'}`].filter(Boolean);
      throw new ConflictException(`This project has ${parts.join(' and ')}. Mark it Cancelled or Completed instead of deleting.`);
    }

    await this.prisma.project.delete({
      where: { tenantId_id: { tenantId, id } },
    });

    return { success: true };
  }

  // Adds or updates a user's membership and role on a project team.
  async addMember(t: RequestTenantContext, projectId: string, dto: AddProjectMemberDto) {
    const tenantId = this.tenant.getRequiredTenantId(t);
    const project = await this.prisma.project.findFirst({
      where: { id: projectId, tenantId },
    });
    if (!project) throw new NotFoundException('Project not found');

    await this.assertActiveUsers(tenantId, [dto.userId]);

    return this.prisma.projectMember.upsert({
      where: {
        tenantId_projectId_userId: {
          tenantId,
          projectId,
          userId: dto.userId,
        },
      },
      create: {
        tenantId,
        projectId,
        userId: dto.userId,
        roleLabel: dto.roleLabel || dto.role || 'Team member',
      },
      update: {
        roleLabel: dto.roleLabel || dto.role || 'Team member',
      },
      include: {
        user: { select: { id: true, name: true, email: true } },
      },
    });
  }

  // Removes a team member from a project.
  async removeMember(t: RequestTenantContext, projectId: string, memberId: string) {
    const tenantId = this.tenant.getRequiredTenantId(t);
    const member = await this.prisma.projectMember.findFirst({
      where: {
        projectId,
        tenantId,
        OR: [{ id: memberId }, { userId: memberId }],
      },
    });
    if (!member) throw new NotFoundException('Project member not found');
    const project = await this.prisma.project.findFirst({ where: { id: projectId, tenantId }, select: { ownerId: true } });
    if (project?.ownerId === member.userId) {
      throw new BadRequestException('The project manager cannot be removed. Change the project manager first.');
    }

    await this.prisma.projectMember.delete({
      where: { tenantId_id: { tenantId, id: member.id } },
    });

    return { success: true };
  }

  // Adds a milestone to a project with sequence ordering.
  async addMilestone(t: RequestTenantContext, projectId: string, dto: CreateMilestoneDto) {
    const tenantId = this.tenant.getRequiredTenantId(t);
    const project = await this.prisma.project.findFirst({
      where: { id: projectId, tenantId },
    });
    if (!project) throw new NotFoundException('Project not found');

    const count = await this.prisma.milestone.count({
      where: { projectId, tenantId },
    });

    const rawDue = dto.dueDate || dto.targetDate;
    const dueDate = rawDue ? new Date(rawDue) : new Date(Date.now() + 14 * 24 * 60 * 60 * 1000);
    const orderIndex = dto.orderIndex !== undefined ? dto.orderIndex : dto.order !== undefined ? dto.order : count;

    return this.prisma.milestone.create({
      data: {
        tenantId,
        projectId,
        title: dto.title,
        dueDate,
        orderIndex,
      },
    });
  }

  // Updates milestone title, due date, order, or completion status.
  async updateMilestone(t: RequestTenantContext, projectId: string, milestoneId: string, dto: UpdateMilestoneDto) {
    const tenantId = this.tenant.getRequiredTenantId(t);
    const milestone = await this.prisma.milestone.findFirst({
      where: { id: milestoneId, projectId, tenantId },
    });
    if (!milestone) throw new NotFoundException('Milestone not found');

    const data: Prisma.MilestoneUpdateInput = {};
    if (dto.title !== undefined) data.title = dto.title;
    if (dto.dueDate !== undefined) data.dueDate = new Date(dto.dueDate);
    if (dto.isDone !== undefined) data.isDone = dto.isDone;
    if (dto.orderIndex !== undefined) data.orderIndex = dto.orderIndex;

    return this.prisma.milestone.update({
      where: { tenantId_id: { tenantId, id: milestoneId } },
      data,
    });
  }

  // Deletes a milestone from a project within tenant scope.
  async deleteMilestone(t: RequestTenantContext, projectId: string, milestoneId: string) {
    const tenantId = this.tenant.getRequiredTenantId(t);
    const milestone = await this.prisma.milestone.findFirst({
      where: { id: milestoneId, projectId, tenantId },
    });
    if (!milestone) throw new NotFoundException('Milestone not found');

    await this.prisma.milestone.delete({
      where: { tenantId_id: { tenantId, id: milestoneId } },
    });

    return { success: true };
  }

  // Returns won deals that can be linked to projects.
  async getWonDeals(t: RequestTenantContext) {
    const tenantId = this.tenant.getRequiredTenantId(t);
    return this.prisma.deal.findMany({
      where: {
        tenantId,
        stage: 'CLOSED_WON',
      },
      select: {
        id: true,
        dealNumber: true,
        title: true,
        amount: true,
        estimatedHours: true,
        accountId: true,
        account: { select: { id: true, name: true } },
      },
      orderBy: { updatedAt: 'desc' },
    });
  }
}
