import { supabase } from '@/config/supabase';

export const teamService = {
  async getTeams({ page = 1, pageSize = 10, orderBy = 'created_at', ascending = false ,    searchQuery = '' 
  } = {}) {
    const from = (page - 1) * pageSize;
    const to = from + pageSize - 1;

    let query  =  supabase
      .from('teams')
      .select(`
        id,
        name,
        description,
        attributes,
        created_at,
        updated_at,
        deleted_at,
        schema_version,
        avatar_url,
        team_membership(
          id,
          user_id,
          role,
          is_creator,
          users(
            id,
            email
          )
        )
      `, { count: 'exact' })
      .is('deleted_at', null)
      .order(orderBy, { ascending })
      .range(from, to);
      
      if (searchQuery) {
        query = query.ilike('name', `%${searchQuery}%`);
      }
  
      const { data, error, count } = await query
        .order(orderBy, { ascending })
        .range(from, to);
  
    
    if (error) {
      console.error('Error fetching teams:', error);
      throw error;
    }
    return {
      data,
      total: count || 0
    };
  },

  // 创建团队
  async createTeam({ name, description, userId }) {
    const { data: team, error: teamError } = await supabase
      .from('teams')
      .insert([
        { 
          name, 
          description 
        }
      ])
      .select()
      .single();

    if (teamError) throw teamError;

    // 创建团队成员关系（创建者）
    const { error: membershipError } = await supabase
      .from('team_membership')
      .insert([
        {
          id:team.id,
          team_id: team.id,
          user_id: userId,
          role: 'OWNER',
          is_creator: true
        }
      ]);

    if (membershipError) throw membershipError;

    return team;
  },

  // 获取单个团队详情
  async getTeamById(teamId) {
    const { data, error } = await supabase
      .from('teams')
      .select(`
        id,
        name,
        description,
        attributes,
        created_at,
        updated_at,
        avatar_url,
        team_membership(
          id,
          user_id,
          role,
          is_creator,
          users(
            id,
            email
          )
        )
      `)
      .eq('id', teamId)
      .single();

    if (error) throw error;
    return data;
  },

  // 更新团队信息
  async updateTeam(teamId, updates) {
    const { data, error } = await supabase
      .from('teams')
      .update(updates)
      .eq('id', teamId)
      .select()
      .single();

    if (error) throw error;
    return data;
  },

  // 添加团队成员
  async addTeamMember(teamId, userId, role = 'MEMBER') {
    const { data, error } = await supabase
      .from('team_membership')
      .insert([
        {
          team_id: teamId,
          user_id: userId,
          role,
          is_creator: false
        }
      ])
      .select()
      .single();

    if (error) throw error;
    return data;
  },

  // 更新成员角色
  async updateMemberRole(teamId, userId, role) {
    const { data, error } = await supabase
      .from('team_membership')
      .update({ role })
      .match({ team_id: teamId, user_id: userId })
      .select()
      .single();

    if (error) throw error;
  },
  async deleteTeam(teamId) {
    const { error: teamError } = await supabase
      .from('teams')
      .delete()
      .eq('id', teamId)
      .select()
    if (teamError) throw teamError;
  },
};