File size: 6,016 Bytes
5c876be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
import { useState, useEffect, useCallback } from 'react';
import { eq, desc, and } from 'drizzle-orm';
import { useDatabase } from './useDatabase';
import { matches } from '../db/schema';

// ─── Types ─────────────────────────────────────────────────────────────────────

type MatchStatus = 'pending' | 'accepted' | 'rejected' | 'completed' | 'cancelled';

interface MatchData {
  id: string;
  rideId: string;
  matchedUserId: string;
  matchedUserFullName: string;
  matchedUserAvatar: string | null;
  matchedUserRating: number | null;
  pickupPoint: string | null;
  pickupLatitude: number | null;
  pickupLongitude: number | null;
  dropoffPoint: string | null;
  dropoffLatitude: number | null;
  dropoffLongitude: number | null;
  status: MatchStatus;
  createdAt: string | null;
  updatedAt: string | null;
}

interface NewMatch {
  id: string;
  rideId: string;
  matchedUserId: string;
  matchedUserFullName: string;
  matchedUserAvatar?: string;
  matchedUserRating?: number;
  pickupPoint?: string;
  pickupLatitude?: number;
  pickupLongitude?: number;
  dropoffPoint?: string;
  dropoffLatitude?: number;
  dropoffLongitude?: number;
}

interface UseMatchesReturn {
  matches: MatchData[];
  pendingMatches: MatchData[];
  activeMatch: MatchData | null;
  loading: boolean;
  createMatch: (data: NewMatch) => Promise<MatchData | null>;
  updateMatchStatus: (matchId: string, status: MatchStatus) => Promise<void>;
  acceptMatch: (matchId: string) => Promise<void>;
  rejectMatch: (matchId: string) => Promise<void>;
  refresh: () => Promise<void>;
}

// ─── Hook ──────────────────────────────────────────────────────────────────────

export function useMatches(rideId?: string): UseMatchesReturn {
  const { db } = useDatabase();
  const [matchesList, setMatchesList] = useState<MatchData[]>([]);
  const [loading, setLoading] = useState(true);

  // ── Load matches ─────────────────────────────────────────────────────────────

  const loadMatches = useCallback(async () => {
    try {
      setLoading(true);

      let results;

      if (rideId) {
        results = await db
          .select()
          .from(matches)
          .where(eq(matches.rideId, rideId))
          .orderBy(desc(matches.createdAt))
          .all();
      } else {
        results = await db
          .select()
          .from(matches)
          .orderBy(desc(matches.createdAt))
          .all();
      }

      setMatchesList(results as MatchData[]);
    } catch (error) {
      console.error('[useMatches] Failed to load matches:', error);
      setMatchesList([]);
    } finally {
      setLoading(false);
    }
  }, [db, rideId]);

  useEffect(() => {
    loadMatches();
  }, [loadMatches]);

  // ── Derived state ────────────────────────────────────────────────────────────

  const pendingMatches = matchesList.filter((m) => m.status === 'pending');
  const activeMatch =
    matchesList.find((m) => m.status === 'accepted') ?? null;

  // ── Create match ─────────────────────────────────────────────────────────────

  const createMatch = useCallback(
    async (data: NewMatch): Promise<MatchData | null> => {
      try {
        await db.insert(matches).values({
          id: data.id,
          rideId: data.rideId,
          matchedUserId: data.matchedUserId,
          matchedUserFullName: data.matchedUserFullName,
          matchedUserAvatar: data.matchedUserAvatar ?? null,
          matchedUserRating: data.matchedUserRating ?? 0,
          pickupPoint: data.pickupPoint ?? null,
          pickupLatitude: data.pickupLatitude ?? null,
          pickupLongitude: data.pickupLongitude ?? null,
          dropoffPoint: data.dropoffPoint ?? null,
          dropoffLatitude: data.dropoffLatitude ?? null,
          dropoffLongitude: data.dropoffLongitude ?? null,
        }).run();

        await loadMatches();

        return matchesList.find((m) => m.id === data.id) ?? null;
      } catch (error) {
        console.error('[useMatches] Failed to create match:', error);
        return null;
      }
    },
    [db, loadMatches, matchesList],
  );

  // ── Update match status ──────────────────────────────────────────────────────

  const updateMatchStatus = useCallback(
    async (matchId: string, status: MatchStatus) => {
      try {
        await db
          .update(matches)
          .set({ status, updatedAt: new Date().toISOString() })
          .where(eq(matches.id, matchId))
          .run();

        await loadMatches();
      } catch (error) {
        console.error('[useMatches] Failed to update match status:', error);
      }
    },
    [db, loadMatches],
  );

  // ── Accept / Reject shortcuts ────────────────────────────────────────────────

  const acceptMatch = useCallback(
    (matchId: string) => updateMatchStatus(matchId, 'accepted'),
    [updateMatchStatus],
  );

  const rejectMatch = useCallback(
    (matchId: string) => updateMatchStatus(matchId, 'rejected'),
    [updateMatchStatus],
  );

  return {
    matches: matchesList,
    pendingMatches,
    activeMatch,
    loading,
    createMatch,
    updateMatchStatus,
    acceptMatch,
    rejectMatch,
    refresh: loadMatches,
  };
}