File size: 3,557 Bytes
7f88bdf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
import { createClient } from "@supabase/supabase-js";
import { readFileSync, existsSync } from "fs";
import { fileURLToPath } from "url";
import { dirname, join } from "path";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// Simple env file parser
function loadEnv(path) {
  if (!existsSync(path)) return {};
  try {
    const content = readFileSync(path, "utf-8");
    const env = {};
    for (const line of content.split("\n")) {
      const match = line.match(/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/);
      if (match) {
        const key = match[1];
        let value = match[2].trim();
        if ((value.startsWith('"') && value.endsWith('"')) || 
            (value.startsWith("'") && value.endsWith("'"))) {
          value = value.slice(1, -1);
        }
        env[key] = value;
      }
    }
    return env;
  } catch (e) {
    return {};
  }
}

const env = loadEnv(join(__dirname, "../apps/web/.env.local"));
const supabaseUrl = env.NEXT_PUBLIC_SUPABASE_URL || process.env.NEXT_PUBLIC_SUPABASE_URL;
const supabaseServiceKey = env.SUPABASE_SERVICE_ROLE_KEY || process.env.SUPABASE_SERVICE_ROLE_KEY;

if (!supabaseUrl || !supabaseServiceKey) {
  console.error("Missing required environment variables (NEXT_PUBLIC_SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY)");
  process.exit(1);
}

const supabase = createClient(supabaseUrl, supabaseServiceKey);

const TEST_EMAIL = "tester@tenderhub.co.ke";
const TEST_PASSWORD = "4567"; // Provided by user

async function main() {
  console.log(`Setting up test user: ${TEST_EMAIL}`);

  // 1. Create User
  const { data: userData, error: userError } = await supabase.auth.admin.createUser({
    email: TEST_EMAIL,
    password: TEST_PASSWORD,
    email_confirm: true
  });

  let userId;

  if (userError) {
    if (userError.message.includes("already registered")) {
        console.log("User already exists, fetching details...");
        const { data: { users }, error: listError } = await supabase.auth.admin.listUsers();
        if (listError) throw listError;
        const existingUser = users.find(u => u.email === TEST_EMAIL);
        userId = existingUser.id;
        
        // Update password anyway to ensure it matches
        await supabase.auth.admin.updateUserById(userId, { password: TEST_PASSWORD });
    } else {
        console.error("Failed to create user:", userError.message);
        process.exit(1);
    }
  } else {
    userId = userData.user.id;
    console.log(`Created user: ${userId}`);
  }

  // 2. Ensure Organization & Membership exists
  let { data: member } = await supabase
    .from("members")
    .select("*, organizations(id, name)")
    .eq("user_id", userId)
    .single();

  if (!member) {
    console.log("Creating organization and membership...");
    const slug = `test-org-${userId.slice(0, 8)}`;
    const { data: org, error: orgErr } = await supabase
      .from("organizations")
      .insert({ name: "Tester Org", slug })
      .select("id")
      .single();

    if (orgErr) throw orgErr;
    console.log(`Created org: ${org.id}`);

    const { error: memberErr } = await supabase
      .from("members")
      .insert({ 
        organization_id: org.id, 
        user_id: userId, 
        role: "owner" 
      });

    if (memberErr) throw memberErr;
    console.log("Created membership");
  } else {
    console.log(`User already belongs to org: ${member.organizations.name}`);
  }

  console.log("✓ Test environment ready!");
}

main().catch(err => {
  console.error("Error:", err.message);
  process.exit(1);
});