// apps/server/src/auth/auth.service.ts
import { Injectable, Inject } from '@nestjs/common';
import { SDK } from 'casdoor-nodejs-sdk';
import { Pool } from 'pg';
import { User, UserRole } from '@nest-pure/shared';

@Injectable()
export class AuthService {
  private casdoorSdk: SDK;

  constructor(@Inject('PG_POOL') private readonly db: Pool) {
    // 初始化 Casdoor SDK
    this.casdoorSdk = new SDK({
      endpoint: process.env.CASDOOR_ENDPOINT!,
      clientId: process.env.CASDOOR_CLIENT_ID!,
      clientSecret: process.env.CASDOOR_CLIENT_SECRET!,
      certificate: '', // 如果没有特殊加密需求可为空
      orgName: process.env.CASDOOR_ORG_NAME!,
      appName: process.env.CASDOOR_APP_NAME!,
    });
  }

  // 1. 获取 Casdoor 登录地址
  getSigninUrl() {
    return this.casdoorSdk.getSigninUrl('http://localhost:8888/callback'); // 后续根据前端地址调整
  }

  // 2. 处理回调并持久化用户
  async handleCallback(code: string): Promise<User> {
    // 换取 Token 和用户信息
    const token = await this.casdoorSdk.getSigninToken(code);
    const userInfo = this.casdoorSdk.parseJwtToken(token);

    // SQL 操作：查找或同步用户到本地 Postgres
    const checkSql = 'SELECT * FROM users WHERE casdoor_uuid = $1';
    const { rows } = await this.db.query(checkSql, [userInfo.id]);

    if (rows.length > 0) {
      return rows[0];
    }

    // 如果是新用户，插入数据库
    const insertSql = `
      INSERT INTO users (casdoor_uuid, username, email, avatar, role)
      VALUES ($1, $2, $3, $4, $5) RETURNING *
    `;
    const newUser = await this.db.query(insertSql, [
      userInfo.id,
      userInfo.name,
      userInfo.email,
      userInfo.avatar,
      UserRole.USER,
    ]);

    return newUser.rows[0];
  }
}

