import { Injectable } from "@nestjs/common"
import { InjectRepository } from "@nestjs/typeorm"
import { Role } from "src/modules/role/entities/role.entity"
import { Repository } from "typeorm"
import { defaultAdmins } from "../../../config/app.config"
import { AuthService } from "../../../modules/auth/v1/auth.service"
import { Auth } from "../../../modules/auth/entities/auth.entity"
import { TeamMemberService } from "../../../modules/team-member/v1/team-member.service"

@Injectable()
export class AdminSeedService {
  constructor(
    private readonly authService: AuthService,
    private readonly teamMemberService: TeamMemberService,
    @InjectRepository(Role)
    private readonly roleRepository: Repository<Role>,
  ) {}

  async run() {
    try {
      for (const admin of defaultAdmins) {
        const isAdminExist = await this.authService.checkAdminExist(admin.email)

        const superAdminRole = await this.roleRepository.findOne({
          where: { name: "Super Admin" },
        })

        const superAdminRoleId = superAdminRole?.id
        console.log("Super Admin Role ID:", superAdminRoleId)

        if (!isAdminExist) {
          const teamMemberResult =
            (await this.teamMemberService.createTeamMember({
              first_name: admin.first_name,
              last_name: admin.last_name,
              email: admin.email,
              role_id: superAdminRoleId,
              status: "active",
            })) as any

          console.log("Team Member Creation Result:", teamMemberResult)

          const teamMemberId = teamMemberResult?.data?.id

          if (!teamMemberId) {
            console.error(`Failed to create team member for ${admin.email}`)
            continue
          }

          console.log(`Team member created with ID: ${teamMemberId}`)

          if (!teamMemberId) {
            console.error(`Failed to create team member for ${admin.email}`)
            continue
          }

          const user = new Auth()
          user.first_name = admin.first_name
          user.last_name = admin.last_name
          user.slug = admin.slug
          user.email = admin.email
          user.password = admin.password
          user.role_id = superAdminRoleId
          user.status = "active"
          user.team_member_id = teamMemberId

          const savedUser = await this.authService.create(user)

          console.log(
            `Admin (${admin.email}) created with team_member_id: ${savedUser}`,
          )
        } else {
          console.log(`Admin ${admin.email} already exists, skipping.`)
        }
      }
    } catch (error) {
      console.error("Error running Admin seeder:", error)
      throw error
    }
  }
}
