import { BadRequestException, ForbiddenException, Injectable, NotFoundException } from '@nestjs/common';
import { Prisma, UserRole } from '@prisma/client';
import { PrismaService } from '../../prisma/prisma.service';
import { RequestTenantContext, TenantQueryHelper } from '../../common/tenancy/tenant-query.helper';
import { assertTenantOwner } from '../../common/crm/crm-record.helper';
import { ListTimesheetsQuery } from './dto/list-timesheets.query';
import { LogTimeDto } from './dto/log-time.dto';
import { UpdateTimeDto } from './dto/update-time.dto';

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

  // Returns paginated time entries with weekly user and team summary metrics.
  async list(t: RequestTenantContext, q: ListTimesheetsQuery) {
    const tenantId = this.tenant.getRequiredTenantId(t);
    const page = q.page || 1;
    const limit = q.limit || 20;
    const skip = (page - 1) * limit;

    const where: Prisma.TimeEntryWhereInput = {
      tenantId,
    };

    const now = new Date();
    const sevenDaysAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);

    if (q.view === 'this_week') {
      where.date = { gte: sevenDaysAgo };
    } else if (q.view === 'mine') {
      where.userId = t.userId;
    } else if (q.view === 'billable') {
      where.isBillable = true;
    }

    if (q.projectId) {
      where.projectId = q.projectId;
    }

    if (q.userId) {
      where.userId = q.userId;
    }

    if (q.startDate || q.endDate) {
      where.date = {
        ...(q.startDate ? { gte: new Date(q.startDate) } : {}),
        ...(q.endDate ? { lte: new Date(q.endDate) } : {}),
      };
    }

    if (q.q?.trim()) {
      const term = q.q.trim();
      where.OR = [{ note: { contains: term } }, { project: { name: { contains: term } } }, { user: { name: { contains: term } } }];
    }

    const [total, items, myWeekEntries, allWeekEntries, activeProjectsCount] = await Promise.all([
      this.prisma.timeEntry.count({ where }),
      this.prisma.timeEntry.findMany({
        where,
        skip,
        take: limit,
        orderBy: [{ date: 'desc' }, { createdAt: 'desc' }],
        include: {
          user: { select: { id: true, name: true, email: true } },
          project: {
            select: {
              id: true,
              projectNumber: true,
              name: true,
              accountId: true,
              account: { select: { id: true, name: true } },
            },
          },
          milestone: { select: { id: true, title: true } },
          task: { select: { id: true, title: true } },
        },
      }),
      this.prisma.timeEntry.findMany({
        where: {
          tenantId,
          userId: t.userId,
          date: { gte: sevenDaysAgo },
        },
        select: { hours: true },
      }),
      this.prisma.timeEntry.findMany({
        where: {
          tenantId,
          date: { gte: sevenDaysAgo },
        },
        select: { hours: true, isBillable: true },
      }),
      this.prisma.project.count({
        where: { tenantId, status: 'Active' },
      }),
    ]);

    const myHoursThisWeek = myWeekEntries.reduce((s, e) => s + Number(e.hours), 0);
    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;

    return {
      data: items,
      meta: {
        total,
        page,
        limit,
        totalPages: Math.ceil(total / limit),
        stats: {
          myHoursThisWeek,
          teamHoursThisWeek,
          billableHoursThisWeek,
          billablePercentThisWeek,
          activeProjectsCount,
        },
      },
    };
  }

  // Retrieves time entry details by ID within tenant scope.
  async get(t: RequestTenantContext, id: string) {
    const tenantId = this.tenant.getRequiredTenantId(t);
    const entry = await this.prisma.timeEntry.findFirst({
      where: { id, tenantId },
      include: {
        user: { select: { id: true, name: true, email: true } },
        project: {
          select: {
            id: true,
            projectNumber: true,
            name: true,
            account: { select: { id: true, name: true } },
          },
        },
        milestone: true,
        task: true,
      },
    });

    if (!entry) {
      throw new NotFoundException('Time entry not found');
    }

    return entry;
  }

  // Logs hours worked on a project with validation and quarter-hour rounding.
  async create(t: RequestTenantContext, dto: LogTimeDto) {
    const tenantId = this.tenant.getRequiredTenantId(t);
    const project = await this.prisma.project.findFirst({
      where: { id: dto.projectId, tenantId },
    });
    if (!project) {
      throw new NotFoundException('Project not found');
    }
    if (project.status === 'Completed' || project.status === 'Cancelled') {
      throw new BadRequestException(`This project is ${project.status.toLowerCase()}. Reopen it before logging time.`);
    }

    if (dto.milestoneId) {
      const milestone = await this.prisma.milestone.findFirst({
        where: {
          id: dto.milestoneId,
          projectId: dto.projectId,
          tenantId,
        },
      });
      if (!milestone) {
        throw new NotFoundException('Milestone not found in this project');
      }
    }

    if (dto.taskId) {
      const task = await this.prisma.task.findFirst({
        where: { id: dto.taskId, tenantId, projectId: dto.projectId },
      });
      if (!task) {
        throw new NotFoundException('Task not found in this project');
      }
    }

    const targetUserId = dto.userId || t.userId!;
    if (targetUserId !== t.userId && t.role !== UserRole.ORGANIZATION_ADMIN) {
      throw new ForbiddenException('You can only log time for yourself');
    }
    await assertTenantOwner(this.prisma, tenantId, targetUserId);

    const entryDate = new Date(dto.date);
    const endOfToday = new Date();
    endOfToday.setHours(23, 59, 59, 999);
    if (entryDate.getTime() > endOfToday.getTime()) {
      throw new BadRequestException('Time entries cannot be logged for future dates');
    }

    const roundedHours = Math.round(dto.hours * 4) / 4;

    return this.prisma.timeEntry.create({
      data: {
        tenantId,
        projectId: dto.projectId,
        milestoneId: dto.milestoneId || null,
        taskId: dto.taskId || null,
        userId: targetUserId,
        date: entryDate,
        hours: roundedHours,
        isBillable: dto.isBillable !== undefined ? dto.isBillable : true,
        note: dto.note || null,
      },
      include: {
        user: { select: { id: true, name: true, email: true } },
        project: { select: { id: true, name: true, projectNumber: true } },
      },
    });
  }

  // Updates time entry fields after verifying ownership or admin status.
  async update(t: RequestTenantContext, id: string, dto: UpdateTimeDto) {
    const tenantId = this.tenant.getRequiredTenantId(t);
    const existing = await this.prisma.timeEntry.findFirst({
      where: { id, tenantId },
    });
    if (!existing) {
      throw new NotFoundException('Time entry not found');
    }

    const isOwner = existing.userId === t.userId;
    const isAdmin = t.role === UserRole.ORGANIZATION_ADMIN;
    if (!isOwner && !isAdmin) {
      throw new ForbiddenException('You can only edit your own time entries');
    }
    if (existing.invoiceId) {
      throw new BadRequestException('This time has already been invoiced and cannot be changed');
    }

    const data: Prisma.TimeEntryUncheckedUpdateInput = {};

    if (dto.date !== undefined) {
      const entryDate = new Date(dto.date);
      const endOfToday = new Date();
      endOfToday.setHours(23, 59, 59, 999);
      if (entryDate.getTime() > endOfToday.getTime()) {
        throw new BadRequestException('Time entries cannot be logged for future dates');
      }
      data.date = entryDate;
    }
    if (dto.hours !== undefined) data.hours = Math.round(dto.hours * 4) / 4;
    if (dto.isBillable !== undefined) data.isBillable = dto.isBillable;
    if (dto.note !== undefined) data.note = dto.note;

    if (dto.projectId && dto.projectId !== existing.projectId) {
      const p = await this.prisma.project.findFirst({
        where: { id: dto.projectId, tenantId },
      });
      if (!p) throw new NotFoundException('Target project not found');
      data.projectId = dto.projectId;
      data.milestoneId = null;
      data.taskId = null;
    }

    return this.prisma.timeEntry.update({
      where: { tenantId_id: { tenantId, id } },
      data,
      include: {
        user: { select: { id: true, name: true, email: true } },
        project: { select: { id: true, name: true, projectNumber: true } },
      },
    });
  }

  // Deletes a time entry after verifying ownership or admin status.
  async remove(t: RequestTenantContext, id: string) {
    const tenantId = this.tenant.getRequiredTenantId(t);
    const existing = await this.prisma.timeEntry.findFirst({
      where: { id, tenantId },
    });
    if (!existing) {
      throw new NotFoundException('Time entry not found');
    }

    const isOwner = existing.userId === t.userId;
    const isAdmin = t.role === UserRole.ORGANIZATION_ADMIN;
    if (!isOwner && !isAdmin) {
      throw new ForbiddenException('You can only delete your own time entries');
    }
    if (existing.invoiceId) {
      throw new BadRequestException('This time has already been invoiced and cannot be deleted');
    }

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

    return { success: true };
  }
}
