import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { PrismaService } from '../../database/prisma.service';
import * as bcrypt from 'bcrypt';

export interface LoginDto {
  account: string;
  password: string;
  role: string;
}

export interface JwtPayload {
  sub: number;
  role: string;
  tenantId?: number;
}

@Injectable()
export class AuthService {
  constructor(
    private prisma: PrismaService,
    private jwtService: JwtService,
  ) {}

  async validateUser(account: string, password: string) {
    // 根据账号查找用户（这里简化处理，实际应根据role查找不同表）
    const user = await this.prisma.teacher.findUnique({
      where: { loginAccount: account },
    });

    if (!user) {
      throw new UnauthorizedException('账号或密码错误');
    }

    const isPasswordValid = await bcrypt.compare(password, user.passwordHash);

    if (!isPasswordValid) {
      throw new UnauthorizedException('账号或密码错误');
    }

    if (user.status !== 'ACTIVE') {
      throw new UnauthorizedException('账号已被停用');
    }

    return user;
  }

  async login(dto: LoginDto) {
    // 根据角色查找不同的用户表
    let user: any;

    if (dto.role === 'admin') {
      // 超管账号（硬编码或从配置读取）
      if (dto.account === 'admin' && dto.password === 'admin123') {
        user = {
          id: 1,
          name: '超级管理员',
          role: 'admin',
        };
      } else {
        throw new UnauthorizedException('账号或密码错误');
      }
    } else if (dto.role === 'school') {
      // 学校管理员（从租户表查找）
      const tenant = await this.prisma.tenant.findUnique({
        where: { loginAccount: dto.account },
      });

      if (!tenant) {
        throw new UnauthorizedException('账号或密码错误');
      }

      // 验证密码
      if (!tenant.passwordHash) {
        throw new UnauthorizedException('账号未设置密码');
      }

      const isPasswordValid = await bcrypt.compare(dto.password, tenant.passwordHash);

      if (!isPasswordValid) {
        throw new UnauthorizedException('账号或密码错误');
      }

      if (tenant.status !== 'ACTIVE') {
        throw new UnauthorizedException('账号已被停用');
      }

      user = {
        id: tenant.id,
        name: tenant.name,
        role: 'school',
        tenantId: tenant.id,
        tenantName: tenant.name,
      };
    } else if (dto.role === 'teacher') {
      // 教师
      const teacher = await this.prisma.teacher.findUnique({
        where: { loginAccount: dto.account },
        include: {
          tenant: {
            select: {
              id: true,
              name: true,
            },
          },
        },
      });

      if (!teacher) {
        throw new UnauthorizedException('账号或密码错误');
      }

      const isPasswordValid = await bcrypt.compare(dto.password, teacher.passwordHash);

      if (!isPasswordValid) {
        throw new UnauthorizedException('账号或密码错误');
      }

      if (teacher.status !== 'ACTIVE') {
        throw new UnauthorizedException('账号已被停用');
      }

      user = {
        id: teacher.id,
        name: teacher.name,
        role: 'teacher',
        tenantId: teacher.tenantId,
        tenantName: teacher.tenant?.name,
      };
    } else if (dto.role === 'parent') {
      // 家长
      const parent = await this.prisma.parent.findUnique({
        where: { loginAccount: dto.account },
        include: {
          tenant: {
            select: {
              id: true,
              name: true,
            },
          },
        },
      });

      if (!parent) {
        throw new UnauthorizedException('账号或密码错误');
      }

      const isPasswordValid = await bcrypt.compare(dto.password, parent.passwordHash);

      if (!isPasswordValid) {
        throw new UnauthorizedException('账号或密码错误');
      }

      if (parent.status !== 'ACTIVE') {
        throw new UnauthorizedException('账号已被停用');
      }

      user = {
        id: parent.id,
        name: parent.name,
        role: 'parent',
        tenantId: parent.tenantId,
        tenantName: parent.tenant?.name,
      };

      // 更新最后登录时间
      await this.prisma.parent.update({
        where: { id: parent.id },
        data: { lastLoginAt: new Date() },
      });
    } else {
      throw new UnauthorizedException('无效的角色');
    }

    // 生成JWT token
    const payload: JwtPayload = {
      sub: user.id,
      role: user.role,
      tenantId: user.tenantId,
    };

    const token = this.jwtService.sign(payload);

    // 更新最后登录时间
    if (dto.role === 'teacher') {
      await this.prisma.teacher.update({
        where: { id: user.id },
        data: { lastLoginAt: new Date() },
      });
    }

    return {
      token,
      user: {
        id: user.id,
        name: user.name,
        role: user.role,
        tenantId: user.tenantId,
        tenantName: user.tenantName,
      },
    };
  }

  async getProfile(userId: number, role: string) {
    if (role === 'admin') {
      return {
        id: 1,
        name: '超级管理员',
        role: 'admin',
      };
    } else if (role === 'school') {
      const tenant = await this.prisma.tenant.findUnique({
        where: { id: userId },
      });

      if (!tenant) {
        throw new UnauthorizedException('用户不存在');
      }

      return {
        id: tenant.id,
        name: tenant.name,
        role: 'school',
        tenantId: tenant.id,
        tenantName: tenant.name,
      };
    } else if (role === 'teacher') {
      const teacher = await this.prisma.teacher.findUnique({
        where: { id: userId },
        include: {
          tenant: {
            select: {
              id: true,
              name: true,
            },
          },
        },
      });

      if (!teacher) {
        throw new UnauthorizedException('用户不存在');
      }

      return {
        id: teacher.id,
        name: teacher.name,
        role: 'teacher',
        tenantId: teacher.tenantId,
        tenantName: teacher.tenant?.name,
        email: teacher.email,
        phone: teacher.phone,
      };
    } else if (role === 'parent') {
      const parent = await this.prisma.parent.findUnique({
        where: { id: userId },
        include: {
          tenant: {
            select: {
              id: true,
              name: true,
            },
          },
          children: {
            include: {
              student: {
                select: {
                  id: true,
                  name: true,
                },
              },
            },
          },
        },
      });

      if (!parent) {
        throw new UnauthorizedException('用户不存在');
      }

      return {
        id: parent.id,
        name: parent.name,
        role: 'parent',
        tenantId: parent.tenantId,
        tenantName: parent.tenant?.name,
        email: parent.email,
        phone: parent.phone,
        children: parent.children.map((c) => ({
          id: c.student.id,
          name: c.student.name,
          relationship: c.relationship,
        })),
      };
    }

    throw new UnauthorizedException('无效的角色');
  }
}
